Java8 Stream duplicate check (write neatly using Collector)

As a method of counting duplicate elements, there is a method of making a Stream a List, getting the length, and then putting it in a Set to compare the lengths, but I'm not happy because it doesn't look like the Stream API. You can write with a good feeling by creating a Collector.

static<T> Collector<T,?,Boolean> uniqueElements(){
    Set<T> set = new HashSet<>();
    return Collectors.reducing(true, set::add, Boolean::logicalAnd);
}

When dealing with parallel streams, it is better to use Thread safe Collection.

The actual usage is as follows;

@Test
public void testUniqueElements(){
    assertTrue(Stream.of("a","b","c").collect(uniqueElements()));
    assertFalse(Stream.of("a","b","b").collect(uniqueElements()));
}
static<T> Collector<T,?,Boolean> uniqueElements(){
    Set<T> set = new HashSet<>();
    return Collectors.reducing(true, set::add, Boolean::logicalAnd);
}

that's all.

Recommended Posts

Java8 Stream duplicate check (write neatly using Collector)
[Java 8] Duplicate deletion (& duplicate check) with Stream
[Java] Element existence check with Stream
I tried using Java8 Stream API
Data processing using stream API from Java 8
Try using the Stream API in Java
Sort by multiple conditions using Java Stream
Write Selenium Java binding code using Silk WebDriver
[Java] How to operate List using Stream API
[JAVA] Stream type
Try Java 8 Stream
Java version check
Java Stream API
Java check process
Studying Java 8 (Stream)
Java Stream termination
[Java] Stream processing
Java 9 Optional :: stream