본문 바로가기
Programming/JAVA

[Java] 배열 요소의 중복을 제거하는 방법

by 쿠쿠씨 2023. 6. 15.
반응형

배열 요소의 중복을 제거하는 방법에 대해 알아보겠습니다.

 

1. Set 사용

Set은 중복 요소를 허용하지 않는 자료구조입니다.

따라서 배열을 Set으로 변환한 뒤 다시 Set을 배열로 변환하는 방법으로 중복을 제거할 수 있습니다.

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class Temp {
    public static void main(String[] args) {
        String[] array = {"A", "B", "C", "B", "D", "A", "E"};
        Set<String> set = new HashSet<>(Arrays.asList(array));
        
        String[] uniqueArray = set.toArray(new String[0]);
        System.out.println(Arrays.toString(uniqueArray));	//[A, B, C, D, E]
    }
}

 

2. ArrayList 사용

ArrayList를 사용하여 배열의 중복을 제거할 수 있습니다.

배열을 ArrayList로 변환하고 새로운 리스트에 중복을 제거하여 저장한 뒤, 배열로 변환합니다.

 

import java.util.ArrayList;
import java.util.Arrays;

public class Temp {
    public static void main(String[] args) {
        String[] array = {"A", "B", "C", "B", "D", "A", "E"};
        ArrayList<String> list = new ArrayList<>(Arrays.asList(array));
        ArrayList<String> uniqueList = new ArrayList<>();
        
        for (String e : list) {
            if (!uniqueList.contains(e)) {	//요소가 없을 경우 요소를 추가합니다.
                uniqueList.add(e);
            }
        }
        
        String[] uniqueArray = uniqueList.toArray(new String[0]);
        System.out.println(Arrays.toString(uniqueArray));	//[A, B, C, D, E]
    }
}

 

3. Java Stream의 distinct() 메서드 사용

Java 8 부터는 Stream의 distinct() 메서드로 중복을 제거할 수 있습니다.

import java.util.Arrays;

public class Temp {
    public static void main(String[] args) {
        String[] array = {"A", "B", "C", "B", "D", "A", "E"};
        String[] uniqueArray = Arrays.stream(array)
                .distinct()
                .toArray(String[]::new);
        System.out.println(Arrays.toString(uniqueArray));	//[A, B, C, D, E]
    }
}

 

반응형

댓글