Java
[Java] List 중복 제거하기
모눈종이씨
2022. 10. 28. 15:59
List에서 중복을 제거하려면 어떻게 해야할까?
Set 이용하기
먼저 List를 Set으로 변경하여 중복을 제거해준다음 다시 List로 반환하는 방법이 있다.
List<Integer> list = List.of(1, 2, 3, 4, 5, 1, 1, 1);
System.out.println("list = " + list);
Set<Integer> set = new HashSet<>(list);
List<Integer> list2 = new ArrayList<>(set);
System.out.println("list2 = " + list2);
/**
* list = [1, 2, 3, 4, 5, 1, 1, 1]
* list2 = [1, 2, 3, 4, 5]
*/
Stream의 distict() 이용하기
Java8부터는 Stream의 distict()를 이용해서 중복을 제거할 수 있다.
List<Integer> list = List.of(1, 2, 3, 4, 5, 1, 1, 1);
List<Integer> collect = list.stream().distinct().collect(Collectors.toList());
System.out.println("collect = " + collect);
/**
* collect = [1, 2, 3, 4, 5]
*/
참고자료
남궁성, 『자바의 정석』, 도우출판