1

I have an object as follows and a list as per the object Type:

public class A{
    private String x;
    private String y;
    private List<A> child = new ArrayList<>();
}

What I want to do is flatten the list and make a list of Object A together with its children;

Currently I am doing in three separate statements as per below:

List<A> ChildElements = map.values()
                .stream()
                .flatMap(entry -> entry.getChild().stream())
                .collect(Collectors.toList());
List<A> RootElements = map.values()
                .stream()
                .collect(Collectors.toList());
List<A> elements = Stream.concat(ChildElements.stream(),RootElements.stream()).collect(Collectors.toList()); 

I wanted to know if the above can be refactored in one statement.

Thank you.

3
  • Why do you want it all in one statement? Commented Aug 8, 2021 at 18:54
  • @Turing85 just for my knowledge and see if it can be written in lesser number of lines of codes. Commented Aug 8, 2021 at 18:55
  • map.values().stream().flatMap(entry -> { final ArraryList<A> result = new ArrayList>(entry.getChild().stream())); result.add(entry); return result.stream(); }).collect(Collectors.toList()); Commented Aug 8, 2021 at 19:00

2 Answers 2

1

It is possible to concat streams immediately in the flatMap:

List<A> flattened = map.values()
        .stream()
        .flatMap(root -> Stream.concat(
            Stream.of(root),
            root.getChildren().stream()
        ))
        .collect(Collectors.toList());

However, initial implementation provides another order of the elements in the results:

initial: child11, child12,... child1N1, child21,... child2N2, ...childMNm, root1,... rootM
flattened: root1, child11,... child1N1,... rootM, childM1... childMNm
Sign up to request clarification or add additional context in comments.

Comments

1

One way would be like following:

map.values()
  .stream()
  .flatMap(entry -> {
    Stream<A> entryStream = Stream.of(entry);
    Stream<A> childStream = entry.getChild().stream();
    return Stream.concat(entryStream, childStream);
  })
  .collect(Collectors.toList());

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.