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.
More filters can be applied in a variety of methods, such using the filter() method twice or supplying another predicate to the Predicate.
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.
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.
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());
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