5

I have a List which looks as follows:

List<List<Class2>> list = new ArrayList<>();

List<Class2> l1 = new ArrayList<>();
l1.add(new Class2(new Class3()));
l1.add(new Class2(new Class3()));
l1.add(new Class2(new Class3()));
list.add(l1);

List<Class2> l2 = new ArrayList<>();
l2.add(new Class2(new Class3()));
l2.add(new Class2(new Class3()));
l2.add(new Class2(new Class3()));
list.add(l2);

How can I convert the List list into a List<Class3> using the Java 8 Stream API?

2
  • Where are your attempts? Commented Sep 29, 2016 at 12:00
  • No attempts yet, except the brute-force method where I iterated over the list and extracted the Class3 object by myself Commented Sep 29, 2016 at 12:11

1 Answer 1

9

Since you are passing to the Class2 constructor an instance of Class3, I'm assuming Class2 has a Class3 member with a getter (lets call the getter getClass3()).

Based on this assumption, you can do the following to get a List<Class3> of all the Class3 members of all the Class2 members of all the lists contained in list :

List<Class3> listOf3 = 
    list.stream()
        .flatMap(List::stream) // convert a Stream<List<Class2>> to Stream<Class2>
        .map(Class2::getClass3) // convert a Stream<Class2> to Stream<Class3>
        .collect(Collectors.toList()); // collect to a List<Class3>
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.