Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two level filtering of list in Java 8

I have a list aList of objects of class A. This aList is member of each element b of another list bList. Each element b is of class B. Structure of class B is as follows:

class B {
    String status;
    String name;
}

Structure of class A is as follows:

class A {
    List<B> bList;
    String status;
}

Now I would like to filter aList as follows:

Final list aListResult should contain object a only if a.status = "Active" as well as each "Active" a of aList should contain bList of only "Active" b objects i.e. if b will be in associated bList if and only if b.status == Active.

How would I achieve that in Java 8, I cannot figure out.

like image 207
Joy Avatar asked Mar 21 '18 12:03

Joy


People also ask

Can we use multiple filters in Java 8?

More filters can be applied in a variety of methods, such using the filter() method twice or supplying another predicate to the Predicate.

Can we use two filters in stream?

The Stream API allows chaining multiple filters. We can leverage this to satisfy the complex filtering criteria described. Besides, we can use the not Predicate if we want to negate conditions.

Can we filter a list in Java?

Filtering a list with Java 8 streams. In the next example, we use a Java 8 stream API to filter a list. The Java stream API is used to filter data to contain only persons older than thirty. Predicate<Person> byAge = person -> person.


1 Answers

I'm assuming you want the output List to contain only active A instances for which all the associated B instances are active:

List<A> aList = ...;
List<A> aListResult = 
    aList.stream()
        .filter(a -> a.getStatus().equals("Active"))
        .filter(a -> a.bList.stream().allMatch(b -> b.getStatus().equals("Active")))
        .collect(Collectors.toList());
like image 185
Eran Avatar answered Oct 30 '22 06:10

Eran