14
18

More than 5 years have passed since last update.

【Java8】Streamで重複削除(& 重複チェック)

Last updated at Posted at 2019-01-11

Stream#distinctを用いたリストの重複削除について書きます。

重複削除

重複削除はdistinctしてからcollectでリストに変更することでできます。

重複削除
List<Integer> list = Arrays.asList(1, 1, 2, 3, 4, 5);
//[1, 2, 3, 4, 5]になる
List<Integer> ans = list.stream().distinct().collect(Collectors.toList());

重複チェック

@swordoneさんから頂いたコード(コメント欄)の方がスマートだったので、重複チェックはこちらを使った方が良いです。

重複チェック
List<Integer> list = Arrays.asList(1, 1, 2, 3, 4, 5);
boolean ans = (list.size() == new HashSet<>(list).size());

旧版

非効率ですがstreamを使う旧版も一応残します。

重複チェック
List<Integer> list = Arrays.asList(1, 1, 2, 3, 4, 5);
boolean ans = (list.size() == list.stream().distinct().count());

参考にさせて頂いた記事

14
18
3

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
14
18