How to filter only specific elements by Java 8 Predicate?

﹥>﹥吖頭↗ 提交于 2020-01-21 05:18:38

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/46773120/how-to-filter-only-specific-elements-by-java-8-predicate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!