检查“流”的所有元素是否相同

时间:2014-09-15 19:36:05

标签: java java-8 predicate java-stream

我正在更改一些旧代码以利用Java 8的功能方面。特别是,我正在使用Guava谓词转到java.util.function.Predicate。其中一个谓词是检查Stream是否是同质的,即由所有相同的元素组成。

在我的旧代码中(使用Guava' s Predicate),我有了这个:

static <T> Predicate<Iterable<T>> isHomogeneous() {
    return new Predicate<Iterable<T>>() {
        public boolean apply(Iterable<T> iterable) {
            return Sets.newHashSet(iterable).size() == 1;
        }
    };
}

这是新版本,使用java.util.function.Predicate

public static Predicate<Stream<?>> isHomogeneous =
    stream -> stream.collect(Collectors.toSet()).size() == 1;

IDE(IntellijIDEA v.12)没有显示任何红色波浪线表示错误,但是当我尝试编译时,我得到了这个:

java: no suitable method found for
collect(java.util.stream.Collector<java.lang.Object,capture#1 of ?,java.util.Set<java.lang.Object>>)
  method java.util.stream.Stream.<R>collect(java.util.function.Supplier<R>,java.util.function.BiConsumer<R,? super capture#2 of ?>,java.util.function.BiConsumer<R,R>) is not applicable
    (cannot infer type-variable(s) R
      (actual and formal argument lists differ in length))
  method java.util.stream.Stream.<R,A>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<capture#2 of ?,capture#4 of ?,java.util.Set<capture#2 of ?>> cannot be converted to java.util.stream.Collector<? super capture#2 of ?,capture#4 of ?,java.util.Set<capture#2 of ?>>))

注意:我认为在流上设置谓词可能不是一个好主意。事实上,在我的代码库中,我只需要List<>。但我仍然对简单的单行isHomogeneous谓词有什么问题感到好奇。

2 个答案:

答案 0 :(得分:13)

另一种选择是使用Stream.distinct并确保在结果流中只获得1个元素。

stream.distinct().limit(2).count() == 1

答案 1 :(得分:-1)

您可能想要做的是使用方法参考,如

static <T> boolean isHomogeneous(Iterable<T> iterable) {
    return Sets.newHashSet(iterable).size() == 1;
}

然后你可以像那样使用它

Iterable<Integer> iterable1 = Lists.newArrayList(1, 1);
Iterable<Integer> iterable2 = Lists.newArrayList(1, 2);

Stream.of(iterable1, iterable2).filter(YourClass::isHomogeneous).collect(Collectors.toList());
相关问题