4
1

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 3 years have passed since last update.

【Java】Listの重複を削除する方法

Posted at

1. Setクラスを使う方法

以下では、HashSetクラスに数値が重複する List を渡し、重複なしのリストに詰め替えています。

        //数値が重複するListを作成
		List<Integer> listWithDuplicates = Arrays.asList(0, 1, 2, 3, 4, 4, 5, 5);

		//HashSetに数値が重複するListを渡し、重複なしのリストに詰め替える
		List<Integer> listWithoutDuplicates = new ArrayList<>(new HashSet<>(listWithDuplicates));

	    System.out.println(listWithoutDuplicates); // 出力 -> [0, 1, 2, 3, 4, 5]

2. Streamのdistinct メソッドを使う方法

以下では、Streamのdistinctメソッドで重複を削除し、新たなListに詰め替えています。

        //数値が重複するListを作成
        List<Integer> listWithDuplicates = Arrays.asList(0, 1, 2, 3, 4, 4, 5, 5);

        //distinct()で重複を削除し、重複なしのリストに詰め替える
	    List<Integer> listWithoutDuplicates = listWithDuplicates.stream()
	     .distinct()
	     .collect(Collectors.toList());

	    System.out.println(listWithoutDuplicates); // 出力 -> [0, 1, 2, 3, 4, 5]

#参考
HowToDoInJava : Java Stream distinct()
HowToDoInJava : How to remove duplicate elements in ArrayList

4
1
0

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
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?