Java/문법

[Java] 배열의 공통 원소 집합 구하기

soowitty 2024. 3. 2. 23:28

 

어떤 배열에서 존재하는 원소들의 집합을 구하고 싶다. 즉, 중복을 제거하고 싶다. 

예를 들어, [1, 3, 2, 1, 4, 5, 1, 4] 라는 배열을 {1, 2, 3, 4, 5}로 만들고 싶은 것이다.

 

그렇다면 자바에서 배열을 집합으로 변경할 수 있는 함수가 있을까?  없다. 

 

배열을 List 객체로 변환해주어 HashSet의 생성자 파라미터로 넣어주면 된다.

그렇게 되면 Set 객체는 중복을 허용하지 않기 때문에 배열의 중복이 제거된다.

import java.util.*;

public class Main {
    public static void main(String[] args) {
        String[] arr = { "a", "b", "c", "a", "c" };

        Set<String> set = new HashSet<>(Arrays.asList(arr));

        System.out.println(set);	// [a, b, c] 출력
    }
}

 

 

그런데, 만약 배열이 int형이라면?

집합을 하나 선언하고, 그 집합에 배열의 원소들을 하나씩 삽입해주어야 한다.

import java.util.*;

public class Main {
	public static void main(String[] args){
    	
        int[] arr = {1, 3, 2, 1, 4, 5, 1, 4};
        
        Set<Integer> set = new HashSet<Integer>();
        
        for(int i : arr){
        	set.add(i);
        }
        
        System.out.println(set);	// [1,2,3,4,5] 출력
    }
}