带比较器的Java 8 Stream过滤器

时间:2017-12-12 13:39:28

标签: java java-stream comparator predicate apache-commons-collection

我想基于MyObject字段过滤values列表。在这种情况下:如果MyObject::getValues上的任何值小于给定value,则谓词为false。我还没有找到使用Stream API执行此操作的方法,因此我尝试了ComparatorPredicate Apache。这是我的尝试:

private Predicate<MyObject> valueGreaterThanOrEqualTo(ValueObject value){
    return myObject -> myObject.getValues().stream()
            .noneMatch(v -> ComparatorPredicate.comparatorPredicate(value, new ValueComparator(), ComparatorPredicate.Criterion.LESS)
                    .evaluate(v));
}

然而,这导致:

Caused by: java.lang.ClassCastException: Cannot cast java.lang.Boolean to com.ValueObject
    at java.lang.Class.cast(Class.java:3369)
    at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
    at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
    at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
    at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175)
    at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
    at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
    at java.util.ArrayList$ArrayListSpliterator.tryAdvance(ArrayList.java:1351)
    at java.util.stream.ReferencePipeline.forEachWithCancel(ReferencePipeline.java:126)
    at java.util.stream.AbstractPipeline.copyIntoWithCancel(AbstractPipeline.java:498)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:485)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
    at java.util.stream.MatchOps$MatchOp.evaluateSequential(MatchOps.java:230)
    at java.util.stream.MatchOps$MatchOp.evaluateSequential(MatchOps.java:196)
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.util.stream.ReferencePipeline.noneMatch(ReferencePipeline.java:459)

所以我的问题是为什么ClassCastException会发生以及如何解决它和/或如何用其他(更好的?)解决方案来解决我的问题?

更新

关于这个问题的一点点更新。第一个问题(ClassCastException)是由我在我的示例中未包含的代码引起的。解决后ComparatorPredicate工作正常,所以如果你喜欢它:去吧。然而,我会接受来自已接受答案的建议,这个建议更简单,并且不涉及使用外部库。特别是因为ComparatorPredicate不会延伸java.util.function.Predicate而是org.apache.commons.collections4.Predicate

1 个答案:

答案 0 :(得分:4)

我不明白为什么你必须使用ComparatorPredicate.comparatorPredicate

怎么样:

private Predicate<MyObject> valueGreaterThanOrEqualTo(ValueObject value){
    ValueComparator comparator = new ValueComparator();
    return myObject -> myObject.getValues().stream()
            .noneMatch(v -> comparator.compare(v,value)<0);
}

这是假设ValueComparator实现Comparator<ValueObject>