6

I would like to replace the following code to utilize Java 8 streams if possible:

final List<Long> myIds = new ArrayList<>();
List<Obj> myObjects = new ArrayList<>();
// myObject populated...

for (final Obj ob : myObjects) {
   myIds.addAll(daoClass.findItemsById(ob.getId()));
}

daoClass.findItemsById returns List<Long>

Can anybody advise the best way to do this via lambdas? Many thanks.

0

3 Answers 3

11
List<Long> myIds = myObjects.stream()
    .map(Obj::getId)
    .map(daoClass::findItemsById)
    .flatMap(Collection::stream)
    .collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

Comments

2

Use flatMap which combines multiple list into a single list.

myObjects.stream()
    .flatMap(ob -> daoClass.findItemsById(ob.getId()).stream())
    .collect(Collectors.toList());

Comments

1

flatMap it!

source.stream()
      .flatMap(e -> daoClass.findItemsById(e.getId).stream())     
      .collect(Collectors.toCollection(ArrayList::new));

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.