행복한 째아의 개발 블로그

[Java] 배열의 중복 값 제거하기 (Stream / Set) 본문

JAVA

[Java] 배열의 중복 값 제거하기 (Stream / Set)

째아 2023. 1. 25. 19:59

Stream

배열을 stream 객체로 변환한 뒤 distinct() 함수를 사용하면 된다.

(stream 함수는 jdk8이상에서만 사용 가능)

import java.util.Arrays;

public class Test04Arrays {

	public static void main(String[] args) {

		int[] sus = new int[] {11, 22, 33, 1, 2, 3, 11, 22, 33, 1, 2, 3};
				
		for (int i : Arrays.stream(sus).distinct().toArray()) {
			System.out.print(i + " ");
		}
	}
	
}

 

 

Set

set은 순서가 없고 데이터 중복이 허용 안되는 자료구조이다.

HashSet을 이용하여 배열의 중복제거가 가능하다.

import java.util.Arrays;

public class Test04Arrays {

	public static void main(String[] args) {

		int[] sus = new int[] {11, 22, 33, 1, 2, 3, 11, 22, 33, 1, 2, 3};
        
		System.out.println(new HashSet<>(Arrays.asList(sus)));
        
        // Arrays.asList(sus) << sus 배열을 List 형태로 변환
        // new HashSet<>(Arrays.asList(sus)) << HashSet으로 중복 제거
	}
	
}

 

이 때, List가 아닌 Array의 형태로 변경하고 싶다면 toArray()를 사용하면 된다.

HashSet<Integer> hs = new HashSet<Integer>(Arrays.asList(sus2));
Integer[] s =  hs.toArray(new Integer[hs.size()]);
for (Object x : s) {
	System.out.println(x);
}
Comments