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.
1 Java Lambda Expressions. Lambda Expressions were added in Java 8. A lambda expression is a short block of code which takes in parameters and returns a value. 2 Syntax. Expressions are limited. ... 3 Using Lambda Expressions. Lambda expressions can be stored in variables if the variable's type is an interface which has only one method.
List addAll () Method in Java with Examples. Last Updated : 02 Jan, 2019. This method appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s iterator.
Use Java's Consumer interface to store a lambda expression in a variable: To use a lambda expression in a method, the method should have a parameter with a single-method interface as its type. Calling the interface's method will run the lambda expression:
where lambda operator can be: Please note: Lambda expressions are just like functions and they accept parameters just like functions. Note that lambda expressions can only be used to implement functional interfaces.
List<Long> myIds = myObjects.stream()
.map(Obj::getId)
.map(daoClass::findItemsById)
.flatMap(Collection::stream)
.collect(Collectors.toList());
Use flatMap which combines multiple list into a single list.
myObjects.stream()
.flatMap(ob -> daoClass.findItemsById(ob.getId()).stream())
.collect(Collectors.toList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With