3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

2つのリストを重複要素を排除して結合する

Last updated at Posted at 2019-10-16

Stream.concat()とdistinct()を組み合わせる

  • 重複要素を排除しつつ2つのリストを結合したい場面に出くわし、StreamAPIを使って綺麗できないものだろうかと調べていたらStream.concat()という便利なモノがあったので、これとdistinct()を組み合わせることで上手くできました。
List<Integer> list1 = List.of(1, 2, 3, 4, 5);
List<Integer> list2 = List.of(0, 4, 5, 6, 7);
  • 上のリストlist1list2を重複要素を排除して結合
List<Integer> result = Stream.concat(list1.stream(), list2.stream())
        .distinct()
        .sorted(Comparator.naturalOrder()) // 昇順でソート
        .collect(Collectors.toList());

result.forEach(System.out::println); // -> 0,1,2,3,4,5,6,7
3
2
2

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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?