我正在改变我的一些旧代码以利用Java 8的功能方面.特别是,我正在使用Guava谓词java.util.function.Predicate
.其中一个谓词是检查a是否Stream
是同质的,即由所有相同的元素组成.
在我的旧代码中(使用Guava Predicate
),我有这个:
staticPredicate > isHomogeneous() { return new Predicate >() { public boolean apply(Iterable iterable) { return Sets.newHashSet(iterable).size() == 1; } }; }
这是新版本,使用java.util.function.Predicate
:
public static Predicate> isHomogeneous = stream -> stream.collect(Collectors.toSet()).size() == 1;
IDE(IntellijIDEA v.12)没有显示任何红色波浪线表示错误,但是当我尝试编译时,我得到了这个:
java: no suitable method found for collect(java.util.stream.Collector>) method java.util.stream.Stream. collect(java.util.function.Supplier ,java.util.function.BiConsumer ,java.util.function.BiConsumer ) is not applicable (cannot infer type-variable(s) R (actual and formal argument lists differ in length)) method java.util.stream.Stream. collect(java.util.stream.Collector super capture#2 of ?,A,R>) is not applicable (cannot infer type-variable(s) R,A,capture#3 of ?,T (argument mismatch; java.util.stream.Collector > cannot be converted to java.util.stream.Collector super capture#2 of ?,capture#4 of ?,java.util.Set >))
注意:我认为在流上有一个谓词可能不是一个好主意.事实上,在我的代码库中,我只需要它List<>
.但我仍然对简单的单行isHomogeneous
谓词有什么问题感到好奇.