I have collection List 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 l = list.stream()
.filter(i -> i.getType().equals(TypeEnum.B) && i.getAmount() > 0)
.collect(Collectors.toList());
I get Foo elements with TypeEnum.B but without TypeEnum.A.
解决方案
Try something like this:
List l = list.stream()
.filter(i -> i.getType().equals(TypeEnum.B) ? i.getAmount() > 0 : true)
.collect(Collectors.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