R111
R111

Reputation: 171

Java 8 lambda for each call method and addAll

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.

Upvotes: 6

Views: 6340

Answers (3)

Hemant Patel
Hemant Patel

Reputation: 3260

Use flatMap which combines multiple list into a single list.

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

Upvotes: 2

Ousmane D.
Ousmane D.

Reputation: 56423

flatMap it!

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

Upvotes: 1

John Kugelman
John Kugelman

Reputation: 361605

List<Long> myIds = myObjects.stream()
    .map(Obj::getId)
    .map(daoClass::findItemsById)
    .flatMap(Collection::stream)
    .collect(Collectors.toList());

Upvotes: 11

Related Questions