Home > OS >  Traverse through linked objects
Traverse through linked objects

Time:11-22

I have this object, where each Rule stores a list of Rules:

public class Rule {

    private String name;
    private String condition;
    private List<String> result;
    private List<Rule> rules;
    private Map<String, List<String>> aliases = Maps.newHashMap();
    private boolean last = false;

}

What is the smartest and most efficient way to traverse through all the linked objects, and insert all the "results" field into a list, regardless the object on which they came from? eventually I'd like to have a list:

List<String> results containing all the results from all the objects.

I've been trying for hours and I'd appreciate your help. To get a list of all the objects themselves will also help me, like flatten the tree.

CodePudding user response:

You can use streams

Here is my recursive version for mapping list of rules to stream of results

  private Stream<String> mapToRules(List<Rule> rules) {
    return Stream.concat(rules.stream()
            .map(Rule::getResult)
            .flatMap(List::stream),
        rules.stream()
            .map(Rule::getRules)
            .flatMap(this::mapToRules));
  }

Version for a single root

  private Stream<String> mapToRules(Rule rule) {
    return Stream.concat(rule
            .getResult()
            .stream(),
        rule.getRules()
            .stream()
            .flatMap(this::mapToRules));
  }

You can then collect this stream to a list

mapToRules(list).collect(Collectors.toList());
  • Related