2

Do you have any idea how to retrieve all SimpleProperty from TopComplexity object? I need to change that for loop into stream "kind" piece of code.

@Data
public class TopComplexity {
   List<SuperComplexProperty> superComplexProperties;
}
@Data
public class SuperComplexProperty {
   List<SimpleProperty> simpleProperties;
   ComplexProperty complexProperty;
}

@Data
public class ComplexProperty {
   List<SimpleProperty> simpleProperties;
}

public class MainClass {
   public static void main(String[] args) {

       TopComplexity top = null;
       List<SimpleProperty> result = new ArrayList<>();
      
       for(SuperComplexProperty prop : top.getSuperComplexProperties) {
          result.addAll(prop.getSimpleProperties());
      
          if(Objects.nonNull(prop.getComplexProperty()) {
              result.addAll(prop.getComplexProperty().getSimpleProperties());
         }
      }
   }
}

Really appreciate any kind of help

2
  • 1
    Stream will not help much here in order to reduce the body of the for loop or its readability. My advice will be change the object design little like adding "public List<SimpleProperty> flatten()" in each object which only takes care for flattenning/summarizing its own complex elements into a simple list (and will invoke nested element's flatten() in turn). Then you only need to call "top.flatten()" and it will return all simple properties that you want. Commented Jul 31, 2020 at 9:53
  • Honestly, it is really simple and good idea. Great thanks Commented Jul 31, 2020 at 10:05

1 Answer 1

2

You can mix up flatMap with a concatenation and ternary operator involving Streams such as:

List<SimpleProperty> result = top.getSuperComplexProperties().stream()
        .flatMap(scp -> Stream.concat(
                scp.getSimpleProperties().stream(),
                scp.getComplexProperty() == null ?
                        Stream.empty() :
                        scp.getComplexProperty().getSimpleProperties().stream()))
        .collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.