How to filter only specific elements of Java 8 Predicate?

I have a collection of List<Foo>elements Foo:

class Foo {
  private TypeEnum type;
  private int amount;

  //getters, setters ...
}

FooIt may be TypeEnum.Aand TypeEnum.B.

I would like to get only those Fooelements from the list that, if the element has type == TypeEnum.B, then amountmore than zero ( amount > 0).

How to do it using Java 8 Streams method filter()?

If I use:

List<Foo> l = list.stream()
    .filter(i -> i.getType().equals(TypeEnum.B) && i.getAmount() > 0)
    .collect(Collectors.<Foo>toList());

I get items Foowith TypeEnum.B, but without TypeEnum.A.

+4
source share
1 answer

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 typeequal TypeEnum.B.

true, type TypeEnum.B amount 0 - TypeEnum.B .

EDIT: Holger ( ) :

!i.getType().equals(TypeEnum.B) || i.getAmount()>0
+5

Source: https://habr.com/ru/post/1687564/


All Articles