kuba44
kuba44

Reputation: 1878

How to filter only specific elements by Java 8 Predicate?

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.

Upvotes: 5

Views: 1713

Answers (1)

Szymon Stepniak
Szymon Stepniak

Reputation: 42184

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

Upvotes: 6

Related Questions