To check if all elements of the "stream" are identical

I'm trying to change some of my old code to take advantage of the functional aspects of Java 8. In particular, I am moving from using Guava predicates to java.util.function.Predicate. One predicate is to check if a is Streamhomogeneous, i.e. Consists of all the same elements.

In my old code (using Guava Predicate) I had this:

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

This is a new version using java.util.function.Predicate:

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

The IDE (IntellijIDEA v.12) does not display a red squiggly line indicating an error, but when I try to compile, I get the following:

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.

+4
2

- Stream.distinct , 1 .

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

, ,

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());
-1

All Articles