Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 738
kuba44 Avatar asked Oct 16 '17 14:10

kuba44


People also ask

Is filter a predicate?

filter() accepts predicate as argument.

Which methods can you use to filter and slice a stream in Java 8 +?

Streams Filtering & Slicing Basics: Java 8 Streams support declarative filtering out of elements along with the ability to slice-off portions of a list. Streams support four operations to achieve this – filter() , distinct() , limit(n) and skip(n) .

How do you filter values in Java?

Java stream provides a method filter() to filter stream elements on the basis of given predicate. Suppose you want to get only even elements of your list then you can do this easily with the help of filter method. This method takes predicate as an argument and returns a stream of consisting of resulted elements.


1 Answers

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
like image 118
Szymon Stepniak Avatar answered Oct 19 '22 15:10

Szymon Stepniak