I often find myself in the need to filter a Stream
or to use a predicate that checks if a given field has a given value.
Say for example I have this POJO:
public class A {
private Integer field;
public A(final Integer field) {
this.field = field;
}
public Integer getField() {
return field;
}
}
And I want to filter a Stream
of objects based on the value of the field
:
final Integer someValue = 42;
Stream.of(new A(42), new A(1729), new A(42), new A(87539319), new A(null))
.filter(a -> Objects.equals(a.getField(), someValue))
...
Would there be a convenience method to generate the predicate for the filter
method? I noticed there is Predicate.isEqual
but it does not fit the need.
I could quite easily write one like this:
public static <T,R> Predicate<T> isEqual(Function<? super T, ? extends R> f, R value) {
return v -> Objects.equals(value, f.apply(v));
}
and use it as:
Stream.of(new A(42), new A(1729), new A(42), new A(87539319), new A(null))
.filter(isEqual(A::getField, someValue))
...
but I'd prefer to reuse an existing method from the JDK if possible.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…