Reputation: 171
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
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
Reputation: 56423
flatMap it!
source.stream()
.flatMap(e -> daoClass.findItemsById(e.getId).stream())
.collect(Collectors.toCollection(ArrayList::new));
Upvotes: 1
Reputation: 361605
List<Long> myIds = myObjects.stream()
.map(Obj::getId)
.map(daoClass::findItemsById)
.flatMap(Collection::stream)
.collect(Collectors.toList());
Upvotes: 11