Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 387
R111 Avatar asked Apr 30 '18 16:04

R111


People also ask

What is lambda expression in Java 8?

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.

What is the use of list addall in Java?

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.

How do I run a lambda expression in a variable?

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 used?

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.


2 Answers

List<Long> myIds = myObjects.stream()
    .map(Obj::getId)
    .map(daoClass::findItemsById)
    .flatMap(Collection::stream)
    .collect(Collectors.toList());
like image 95
John Kugelman Avatar answered Nov 11 '22 20:11

John Kugelman


Use flatMap which combines multiple list into a single list.

myObjects.stream()
    .flatMap(ob -> daoClass.findItemsById(ob.getId()).stream())
    .collect(Collectors.toList());
like image 28
Pratapi Hemant Patel Avatar answered Nov 11 '22 20:11

Pratapi Hemant Patel