如何通过Java 8谓词仅过滤特定元素? [英] How to filter only specific elements by Java 8 Predicate?
问题描述
我有Foo
个元素的集合List<Foo>
:
class Foo {
private TypeEnum type;
private int amount;
//getters, setters ...
}
Foo
类型可以是TypeEnum.A
和TypeEnum.B
.
我只想从列表中获取那些Foo
元素,如果该元素具有type == TypeEnum.B
,则amount
大于零(amount > 0
).
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
).
如何通过Java 8 Streams filter()
方法做到这一点?
How can I do it by Java 8 Streams filter()
method?
如果我使用:
List<Foo> l = list.stream()
.filter(i -> i.getType().equals(TypeEnum.B) && i.getAmount() > 0)
.collect(Collectors.<Foo>toList());
我得到具有TypeEnum.B
但没有TypeEnum.A
的Foo
元素.
I get Foo
elements with TypeEnum.B
but without TypeEnum.A
.
推荐答案
尝试如下操作:
List<Foo> l = list.stream()
.filter(i -> i.getType().equals(TypeEnum.B) ? i.getAmount() > 0 : true)
.collect(Collectors.<Foo>toList());
仅在type
等于TypeEnum.B
时才检查i.getAmount() > 0
.
在上一次尝试中,只有当type
为TypeEnum.B
并且amount
大于0时,您的谓词才为true
.这就是为什么您仅得到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.
您还可以在评论部分中查看 Holger (与他分享一些积分)提出的建议,使用更短的表达式:
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
这篇关于如何通过Java 8谓词仅过滤特定元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!