如何通过Java 8谓词仅过滤特定元素? [英] How to filter only specific elements by Java 8 Predicate?

查看:94
本文介绍了如何通过Java 8谓词仅过滤特定元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有Foo个元素的集合List<Foo>:

class Foo {
  private TypeEnum type;
  private int amount;

  //getters, setters ...
}

Foo类型可以是TypeEnum.ATypeEnum.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.AFoo元素.

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.

在上一次尝试中,只有当typeTypeEnum.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆