List 중복 제거

자바에서 List에 있는 값들 중에 중복된 값만 제외시키고 싶은 경우가 있다.
루프를 돌면서 유니크한 값인지 비교하는 로직을 사용하고 싶지 않았다.
중복을 허용하지 않는 HashSet으로 변환시키고 다시 List로 변환시키면 유니크한 값으로 이루어진 List를 만들 수 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Sample {
 
    public static void main(String args[]) {
 
        List<String> items = new ArrayList<>();
        items.add("a");
        items.add("b");
        items.add("c");
        items.add("b");
        items.add("c");
        System.out.println(items); // ["a", "b", "c", "b", "c"]
 
  items = new ArrayList<>(new HashSet<>(items)); 
        System.out.println(items); // ["a", "b", "c"]
    }
}

cs

대소문자까지 중복된 값을 제외시킬 수 있는 좋은 방법 있으시면 피드백 부탁드립니다~

'Development > Java' 카테고리의 다른 글

Garbage Collection 과정  (0) 2018.04.28
Garbage Collection 용어 정리  (0) 2018.04.26
AES256 암호화 오류 해결  (4) 2017.10.06
반복문 성능 비교  (0) 2017.07.27
Reflection 클래스 정보  (0) 2017.07.12

+ Recent posts