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