Java/컬렉션

[Java]ArrayList 중복 제거

DevStory 2022. 6. 27.

이번 포스팅은 ArrayList에서 중복 요소를 제거하는 방법을 소개합니다.


방법 1. 반복문

가장 기초적인 방법으로 새로운 ArrayList를 만들고 이전 ArrayList를 순회하여 새로운 ArrayList에 요소를 추가합니다. 새로운 ArrayList에 추가된 요소가 존재하는 경우 중복 요소가 존재한다는 의미이므로 요소를 추가하지 않습니다.

 

다음 예제는 반복문을 사용하여 중복 요소가 없는 새로운 ArrayList를 만듭니다.

public class Main {
  public static void main(String args[]) {
    ArrayList<String> oldLi = new ArrayList<String>();
    oldLi.add("A");
    oldLi.add("AB");
    oldLi.add("AB");
    oldLi.add("ABC");
    oldLi.add("ABCD");
    oldLi.add("ABCD");

    ArrayList<String> newLi = new ArrayList<String>();

    // 중복 요소가 존재하는 기존 ArrayList
    System.out.println("oldLi: " + oldLi);

    // 새로운 ArrayList에 요소를 추가
    for(String strValue : oldLi) {
      // 중복 요소가 없는 경우 요소를 추가
      if(!newLi.contains(strValue)) {
        newLi.add(strValue);
      }
    }

    // 중복 요소를 제거한 새로운 ArrayList
    System.out.println("newLi: " + newLi);
  }
}

실행 결과

oldLi: [A, AB, AB, ABC, ABCD, ABCD]
newLi: [A, AB, ABC, ABCD]

방법 2. HashSet으로 변환

HashSet은 고유한 요소만 가지므로 ArrayList를 HashSet으로 변환하여 중복 요소를 제거할 수 있습니다. 이 방법의 문제점은 순서가 유지되지 않습니다.

 

다음 예제는 ArrayList를 HashSet으로 변환하여 중복 요소를 제거합니다.

public class Main {
  public static void main(String args[]) {
    ArrayList<String> li = new ArrayList<String>();
    li.add("ABCD");
    li.add("ABCD");
    li.add("A");
    li.add("ABC");
    li.add("AB");
    li.add("AB");

    System.out.println("중복 요소 제거 전: " + li);

    // HashSet으로 변환
    HashSet<String> hs = new HashSet<String>(li);
    // 기존 ArrayList 클리어
    li.clear();
    // 중복 요소가 제거된 HashSet을 추가
    li.addAll(hs);

    System.out.println("중복 요소 제거 후: " + li);
  }
}

실행 결과

중복 요소 제거 전: [ABCD, ABCD, A, ABC, AB, AB]
중복 요소 제거 후: [A, AB, ABC, ABCD]

방법 3. LinkedHashSet으로 변환

LinkedHashSet으로 변환하여 ArrayList의 중복 요소를 제거할 수 있습니다. 이 방법은 HastSet과 유사하며 삽입 순서를 유지한다는 차이점이 있습니다.

 

다음 예제는 ArrayList를 LinkedHashSet으로 변환하여 중복 요소를 제거합니다.

public class Main {
  public static void main(String args[]) {
    ArrayList<String> li = new ArrayList<String>();
    li.add("ABCD");
    li.add("ABCD");
    li.add("A");
    li.add("ABC");
    li.add("AB");
    li.add("AB");

    System.out.println("중복 요소 제거 전: " + li);

    // LinkedHashSet으로 변환
    LinkedHashSet<String> li_hs = new LinkedHashSet<String>(li);
    // 기존 ArrayList 클리어
    li.clear();
    // 중복 요소가 제거된 LinkedHashSet을 추가
    li.addAll(li_hs);

    System.out.println("중복 요소 제거 후: " + li);
  }
}

실행 결과

중복 요소 제거 전: [ABCD, ABCD, A, ABC, AB, AB]
중복 요소 제거 후: [ABCD, A, ABC, AB]

방법 4. Stream API

Java 8 Version 이상인 경우 Stream API의 distinct() 메서드를 사용하여 중복 요소를 제거할 수 있습니다.

 

다음 예제는 Stream API의 distinct() 메서드를 사용하여 ArrayList의 중복 요소를 제거합니다.

public class Main {
  public static void main(String args[]) {
    ArrayList<String> li = new ArrayList<String>();
    li.add("ABCD");
    li.add("ABCD");
    li.add("A");
    li.add("ABC");
    li.add("AB");
    li.add("AB");

    System.out.println("중복 요소 제거 전: " + li);

    li = new ArrayList<String>(
            li.stream().distinct()
                       .collect(Collectors.toList())
    );

    System.out.println("중복 요소 제거 후: " + li);
  }
}

실행 결과

중복 요소 제거 전: [ABCD, ABCD, A, ABC, AB, AB]
중복 요소 제거 후: [ABCD, A, ABC, AB]
반응형

'Java > 컬렉션' 카테고리의 다른 글

[Java]Stack 특정 값 존재하는지 확인하는 방법  (0) 2022.08.23
[Java]HashMap 순회하는 방법  (0) 2022.06.27
[Java]HashSet 정렬  (0) 2022.06.27
[Java]ArrayList 정렬  (0) 2022.06.23
[Java]ArrayList 특정 위치에 값 추가  (0) 2022.06.23

댓글