I have collection List<Foo>
of Foo
elements:
class Foo {
private TypeEnum type;
private int amount;
//getters, setters ...
}
Foo
type can be TypeEnum.A
and TypeEnum.B
.
I would like to get only those Foo
elements from list which if the element have type == TypeEnum.B
then amount
is greater than zero (amount > 0
).
How can I do it by Java 8 Streams filter()
method?
If I use:
List<Foo> l = list.stream()
.filter(i -> i.getType().equals(TypeEnum.B) && i.getAmount() > 0)
.collect(Collectors.<Foo>toList());
I get Foo
elements with TypeEnum.B
but without TypeEnum.A
.
filter() accepts predicate as argument.
Streams Filtering & Slicing Basics: Java 8 Streams support declarative filtering out of elements along with the ability to slice-off portions of a list. Streams support four operations to achieve this – filter() , distinct() , limit(n) and skip(n) .
Java stream provides a method filter() to filter stream elements on the basis of given predicate. Suppose you want to get only even elements of your list then you can do this easily with the help of filter method. This method takes predicate as an argument and returns a stream of consisting of resulted elements.
Try something like this:
List<Foo> l = list.stream()
.filter(i -> i.getType().equals(TypeEnum.B) ? i.getAmount() > 0 : true)
.collect(Collectors.<Foo>toList());
It checks if i.getAmount() > 0
only if type
is equal to TypeEnum.B
.
In your previous attempt your predicate was true
only if type
was TypeEnum.B
and amount
was greater than 0 - that's why you got only TypeEnum.B
in return.
EDIT: you can also check a suggestion made by Holger (share some credits with him) in the comments section and use even shorter version of the expression:
!i.getType().equals(TypeEnum.B) || i.getAmount()>0
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