ArrayList 중복 제거

JavaBeginner
지금 연습하기

소개

Java 에서 ArrayList는 중복된 요소를 저장할 수 있습니다. 중복을 제거하고 고유한 요소만 유지하려면 특정 단계를 거쳐야 합니다. 이 Lab 에서는 HashSet을 사용하고 Streamdistinct() 메서드를 사용하여 ArrayList에서 중복을 제거하는 두 가지 방법을 배웁니다.

ArrayList 생성

ArrayList 를 생성하고 몇 가지 요소를 추가합니다. 다음은 예시입니다.

import java.util.ArrayList;

public class RemoveDuplicates {
    public static void main(String[] args) {
        ArrayList<Integer> arrayList = new ArrayList<>();
        arrayList.add(1);
        arrayList.add(2);
        arrayList.add(3);
        arrayList.add(1);
        arrayList.add(4);
        arrayList.add(2);
        System.out.println("Original ArrayList: " + arrayList);
    }
}

터미널에서 코드를 실행하려면, 해당 파일이 있는 디렉토리로 이동하여 다음 명령을 입력합니다.

javac RemoveDuplicates.java && java RemoveDuplicates

HashSet 을 사용하여 중복 제거

HashSet을 사용하여 중복을 제거하려면, 먼저 HashSet을 생성하고 ArrayList를 해당 생성자에 전달합니다. HashSet은 고유한 요소만 포함하므로, 이 과정에서 모든 중복이 제거됩니다. 결과로 생성된 HashSet을 다시 ArrayList로 변환합니다.

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

public class RemoveDuplicates {
    public static void main(String[] args) {
        ArrayList<Integer> arrayList = new ArrayList<>();
        arrayList.add(1);
        arrayList.add(2);
        arrayList.add(3);
        arrayList.add(1);
        arrayList.add(4);
        arrayList.add(2);
        System.out.println("Original ArrayList: " + arrayList);

        // Remove duplicates
        HashSet<Integer> hashSet = new HashSet<>(arrayList);
        arrayList.clear();
        arrayList.addAll(hashSet);

        System.out.println("ArrayList with duplicates removed using HashSet: " + arrayList);
    }
}

Stream 의 distinct() 메서드를 사용하여 중복 제거

Stream API 를 사용하여 중복을 제거하려면, 먼저 ArrayListstream() 메서드를 사용하여 Stream을 생성합니다. 그런 다음 distinct() 메서드를 사용하여 고유한 요소로 구성된 새로운 스트림을 반환합니다. 마지막으로, collect() 메서드를 사용하여 스트림 요소를 ArrayList로 반환합니다.

import java.util.ArrayList;

public class RemoveDuplicates {
    public static void main(String[] args) {
        ArrayList<Integer> arrayList = new ArrayList<>();
        arrayList.add(1);
        arrayList.add(2);
        arrayList.add(3);
        arrayList.add(1);
        arrayList.add(4);
        arrayList.add(2);
        System.out.println("Original ArrayList: " + arrayList);

        // Remove duplicates
        arrayList = (ArrayList<Integer>) arrayList.stream().distinct().collect(Collectors.toList());

        System.out.println("ArrayList with duplicates removed using Stream: " + arrayList);
    }
}

두 가지 방법 모두 테스트

두 가지 접근 방식을 테스트하려면, 터미널에서 두 코드 예제를 컴파일하고 실행합니다.

javac RemoveDuplicates.java && java RemoveDuplicates

함수 생성

프로그램에서 여러 ArrayList에서 중복을 쉽게 제거하기 위해 함수를 생성할 수 있습니다. 다음은 예시입니다.

import java.util.ArrayList;
import java.util.HashSet;
import java.util.stream.Collectors;

public class RemoveDuplicates {
    public static void main(String[] args) {
        ArrayList<Integer> arrayList1 = new ArrayList<>();
        arrayList1.add(1);
        arrayList1.add(2);
        arrayList1.add(3);
        arrayList1.add(1);
        arrayList1.add(4);
        arrayList1.add(2);
        System.out.println("Original ArrayList: " + arrayList1);

        ArrayList<Integer> arrayList2 = new ArrayList<>();
        arrayList2.add(5);
        arrayList2.add(6);
        arrayList2.add(1);
        arrayList2.add(7);
        arrayList2.add(5);
        System.out.println("Original ArrayList: " + arrayList2);

        // Remove duplicates using HashSet
        removeDuplicatesUsingHashSet(arrayList1);
        removeDuplicatesUsingHashSet(arrayList2);

        // Remove duplicates using Stream
        removeDuplicatesUsingStream(arrayList1);
        removeDuplicatesUsingStream(arrayList2);

    }

    public static void removeDuplicatesUsingHashSet(ArrayList<Integer> arrayList) {
        HashSet<Integer> hashSet = new HashSet<>(arrayList);
        arrayList.clear();
        arrayList.addAll(hashSet);

        System.out.println("ArrayList with duplicates removed using HashSet: " + arrayList);
    }

    public static void removeDuplicatesUsingStream(ArrayList<Integer> arrayList) {
        arrayList = (ArrayList<Integer>) arrayList.stream().distinct().collect(Collectors.toList());
        System.out.println("ArrayList with duplicates removed using Stream: " + arrayList);
    }
}

컴파일 및 실행

터미널에서 코드를 실행하려면, 해당 파일이 있는 디렉토리로 이동하여 다음 명령어를 입력합니다.

javac RemoveDuplicates.java && java RemoveDuplicates

데이터 타입 수정

removeDuplicatesUsingHashSet() 함수는 ArrayList<Integer>에 대해서만 작동합니다. 이 함수를 더 유연하게 만들기 위해 데이터 타입을 ArrayList<T>로 수정할 수 있습니다.

import java.util.ArrayList;
import java.util.HashSet;
import java.util.stream.Collectors;

public class RemoveDuplicates<T> {
    public static void main(String[] args) {
        ArrayList<Integer> arrayList1 = new ArrayList<>();
        arrayList1.add(1);
        arrayList1.add(2);
        arrayList1.add(3);
        arrayList1.add(1);
        arrayList1.add(4);
        arrayList1.add(2);
        System.out.println("Original ArrayList: " + arrayList1);

        ArrayList<String> arrayList2 = new ArrayList<>();
        arrayList2.add("Hello");
        arrayList2.add("World");
        arrayList2.add("Java");
        arrayList2.add("Hello");
        arrayList2.add("Mars");
        System.out.println("Original ArrayList: " + arrayList2);

        // Remove duplicates using HashSet
        removeDuplicatesUsingHashSet(arrayList1);
        removeDuplicatesUsingHashSet(arrayList2);

        // Remove duplicates using Stream
        removeDuplicatesUsingStream(arrayList1);
        removeDuplicatesUsingStream(arrayList2);

    }

    public static <T> void removeDuplicatesUsingHashSet(ArrayList<T> arrayList) {
        HashSet<T> hashSet = new HashSet<>(arrayList);
        arrayList.clear();
        arrayList.addAll(hashSet);

        System.out.println("ArrayList with duplicates removed using HashSet: " + arrayList);
    }

    public static <T> void removeDuplicatesUsingStream(ArrayList<T> arrayList) {
        arrayList = (ArrayList<T>) arrayList.stream().distinct().collect(Collectors.toList());
        System.out.println("ArrayList with duplicates removed using Stream: " + arrayList);
    }
}

수정된 버전 컴파일 및 실행

터미널에서 코드를 실행하려면, 해당 파일이 있는 디렉토리로 이동하여 다음 명령어를 입력합니다.

javac RemoveDuplicates.java && java RemoveDuplicates

사용자 입력 추가

프로그램을 더 상호작용적으로 만들기 위해, 사용자가 ArrayList 에 추가하려는 정수를 입력하도록 할 수 있습니다. 다음은 예시입니다.

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Scanner;
import java.util.stream.Collectors;

public class RemoveDuplicates<T> {
    public static void main(String[] args) {
        ArrayList<Integer> arrayList1 = new ArrayList<>();
        int input = getUserInput();
        while (input != -1) {
            arrayList1.add(input);
            input = getUserInput();
        }
        System.out.println("Original ArrayList: " + arrayList1);

        // Remove duplicates using HashSet
        removeDuplicatesUsingHashSet(arrayList1);

        // Remove duplicates using Stream
        removeDuplicatesUsingStream(arrayList1);

    }

    public static <T> void removeDuplicatesUsingHashSet(ArrayList<T> arrayList) {
        HashSet<T> hashSet = new HashSet<>(arrayList);
        arrayList.clear();
        arrayList.addAll(hashSet);

        System.out.println("ArrayList with duplicates removed using HashSet: " + arrayList);
    }

    public static <T> void removeDuplicatesUsingStream(ArrayList<T> arrayList) {
        arrayList = (ArrayList<T>) arrayList.stream().distinct().collect(Collectors.toList());
        System.out.println("ArrayList with duplicates removed using Stream: " + arrayList);
    }

    public static int getUserInput() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter an integer to add to the ArrayList, or -1 to quit: ");
        if (scanner.hasNextInt()) {
            return scanner.nextInt();
        }
        return -1;
    }
}

최종 버전 컴파일 및 실행

터미널에서 코드를 실행하려면, 해당 파일이 있는 디렉토리로 이동하여 다음 명령어를 입력합니다.

javac RemoveDuplicates.java && java RemoveDuplicates

요약

이 랩에서는 HashSet을 사용하고 Streamdistinct() 메서드를 사용하여 ArrayList에서 중복을 제거하는 두 가지 방법을 배웠습니다. 또한 프로그램에서 여러 ArrayList에서 중복을 더 쉽게 제거할 수 있도록 함수를 만들고, 함수의 유연성을 높이기 위해 데이터 타입을 수정했으며, 사용자가 ArrayList에 추가하려는 정수를 입력할 수 있도록 했습니다.