LoginSignup
1
1

More than 3 years have passed since last update.

Java8 Streamの重複チェック (Collectorを使ってきれいに書く)

Posted at

重複要素を数える方法として、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);
}

以上です。

1
1
9

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1