Java ArrayList 를 HashSet 으로 변환하기

JavaBeginner
지금 연습하기

소개

이 랩에서는 Java 에서 ArrayList 를 HashSet 으로 변환하는 방법을 배우게 됩니다. HashSet 은 중복을 허용하지 않는 컬렉션이므로, ArrayList 를 HashSet 으로 변환하면 ArrayList 에서 모든 중복 요소를 제거할 수 있습니다. add() 메서드, HashSet 생성자 또는 Stream API 를 사용하여 ArrayList 를 HashSet 으로 변환할 수 있습니다.

필요한 패키지 임포트

ArrayList 와 HashSet 패키지를 임포트해야 합니다. 파일에 다음 코드를 추가하십시오:

import java.util.ArrayList;
import java.util.HashSet;

ArrayList 생성

몇 가지 요소를 가진 ArrayList 를 생성합니다. add() 메서드를 사용하여 ArrayList 에 요소를 추가합니다. 다음은 예시입니다:

ArrayList<String> arrList = new ArrayList<>();
arrList.add("Mango");
arrList.add("Apple");
arrList.add("Orange");
arrList.add("Apple");
System.out.println(arrList);

HashSet 생성자를 사용하여 ArrayList 를 HashSet 으로 변환

HashSet 생성자를 사용하여 ArrayList 를 HashSet 으로 변환할 수 있습니다. 다음은 예시입니다:

HashSet<String> hashSet = new HashSet<String>(arrList);
System.out.println("HashSet:");
System.out.println(hashSet);

add() 메서드를 사용하여 ArrayList 를 HashSet 으로 변환

add() 메서드를 사용하여 ArrayList 의 각 요소를 하나씩 HashSet 에 추가하여 고유한 요소 컬렉션을 얻을 수 있습니다. 다음은 예시입니다:

HashSet<String> hashSet = new HashSet<String>();
for (String arr : arrList) {
    hashSet.add(arr);
}
System.out.println("HashSet:");
System.out.println(hashSet);

Stream API 를 사용하여 ArrayList 를 HashSet 으로 변환

Java 8 이상 버전을 사용하고 있다면 Stream API 를 사용하여 변환 코드를 더욱 간결하고 컴팩트하게 만들 수 있습니다. 다음은 예시입니다:

HashSet<String> hashSet = arrList.stream().collect(Collectors.toCollection(HashSet::new));
System.out.println("HashSet:");
System.out.println(hashSet);

파일 저장 및 컴파일

모든 코드를 추가한 후, Ctrl+X를 사용하여 파일을 저장한 다음, Y를 누르고 Enter를 눌러 확인합니다. 파일을 컴파일하려면 터미널에 다음 명령을 입력합니다:

javac ~/project/ArrayListToHashSet.java

프로그램 실행

프로그램을 컴파일한 후, 터미널에 다음 명령을 입력하여 프로그램을 실행합니다:

java ArrayListToHashSet

요약

이 랩에서는 HashSet 생성자, add() 메서드 및 Stream API 를 사용하여 Java 에서 ArrayList 를 HashSet 으로 변환하는 방법을 배웠습니다. 이러한 기술을 적용하여 ArrayList 에서 고유한 요소의 컬렉션을 쉽게 얻을 수 있습니다.