0

I have this situation:

Class Employee{
//some attributes
List<String> idContract

//getter, setter
}

And I need to retrieve a List idContracts from a list using java 8 stream.

I was trying something like that:

lst.stream().filter(o->!o.getLstDipFuoriSoglia().isEmpty())
      .map(ResultOdg::getLstDipFuoriSoglia)
      .collect(Collectors.toList());

but that, of course, returns a List< List < String >>, so how can I achieve that goal?

Thanks for your answers

4
  • 5
    Use flatMap. docs.oracle.com/javase/8/docs/api/java/util/stream/… Commented Jan 20, 2020 at 16:14
  • Just need to change map to flatMap? Nothing else? Commented Jan 20, 2020 at 16:15
  • 3
    Leave the .map as it is, and add .flatMap(List::stream). Commented Jan 20, 2020 at 16:17
  • 1
    What is getLstDipFuoriSoglia in the code? Is lst a List<Employee>? How is ResultOdg defined? Commented Jan 21, 2020 at 2:32

1 Answer 1

7

Just add flatMap operation for converting List to Stream

lst.stream().filter(o->!o.getLstDipFuoriSoglia().isEmpty)
            .map(ResultOdg::getLstDipFuoriSoglia)
            .flatMap(List::stream)
            .collect(Collectors.toList());

Or you can have one flatMap operation

lst.stream().filter(o->!o.getLstDipFuoriSoglia().isEmpty)
            .flatMap(list->list.getLstDipFuoriSoglia().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.