Outsider's Dev Story

Stay Hungry. Stay Foolish. Don't Be Satisfied.

List에서 중복요소 제거한 List로 만들기

자바에서 List를 사용하다가 List가 가진 요소들중 중복된 것을 제거하고 유일한 값들만 가지고 있는 List를 만들어야 할 필요가 있었습니다. 루프를 돌면서 유니크한 값을 찾아서 새로운 배열을 만들자니 약간 귀찮았는데 해쉬셋을 이용해서 간단하게 유일한 요소들만 가진 List로 만들 수 있더군요.


List<Integer> items = new ArrayList<Integer>();
items.add(1);
items.add(2);
items.add(1);
items.add(2);
items.add(3);
items.add(3);
System.out.println(items); // [1, 2, 1, 2, 3, 3]

List<Integer> uniqueItems = new ArrayList<Integer>(new HashSet<Integer>(items));
System.out.println(uniqueItems); // [1, 2, 3]

중복되는 요소들을 가질 리스트를 HashSet으로만든뒤에 다시 List로 변환을 하면 중복요소가 사라진 유일한 요소들만 가진 리스트를 만들 수 있습니다.



덧) 저의 경우에는 필요치 않았지만 HashSet을 사용할 경우 순서가 지켜지지 않을 수 있다는 얘기가 있었습니다.

덧2) 김은석님이 List의 contains와의 성능비교를 공유해 주셨습니다.
2011/10/24 01:04 2011/10/24 01:04