我想根据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

最佳答案

我不明白为什么您必须使用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>

07-24 14:26