Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return from forEach lambda while filtering over a collection of iterable element

Tags:

lambda

java-8

I have one List of elements . Inside the list element in my case say Bean i have another list . My requirement is like , While iterating over the parent list i have to check for a specific condition in the list obtained from Bean class getList()and have to return a boolean from there . Below is a demo of code what i want to achieve . How to achieve this in JAVA -8 using lambda .?

public boolean test(List<Bean> parentList) {

    //Bean is having another List of Bean1
    // i want to do some thing like below 
     parentList.forEach(bean ->   
      bean.getList().stream().
               filter(somePredicate).
               findFirst().isPresent();
 }
like image 766
Deepak Avatar asked Mar 09 '23 20:03

Deepak


1 Answers

You should use Stream::flatMap and check your condition:

parentList.stream().flatMap(bean -> bean.getList().stream()).anyMatch(somePredicate);
like image 171
Flown Avatar answered May 10 '23 21:05

Flown