重複要素を数える方法として、StreamをListにして長さを取得して、さらにSetに入れて長さを比較したりする方法があるが、あまりStream APIっぽくなくうれしくない。
Collectorを作ることでいい感じで書ける。
static<T> Collector<T,?,Boolean> uniqueElements(){
Set<T> set = new HashSet<>();
return Collectors.reducing(true, set::add, Boolean::logicalAnd);
}
並列ストリームを扱う時はThread safeなCollectionを使うとよいです。
実際の使い方は以下の形;
@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);
}
以上です。