List<String>에서 중복 데이터 처리 방법

2024. 11. 7. 22:34Java

중복 데이터 삭제(차집합)

import java.util.ArrayList;
import java.util.List;

public class RemoveDuplicates {
    public static void main(String[] args) {
        List<String> list1 = new ArrayList<>(List.of("apple", "banana", "orange", "grape"));
        List<String> list2 = new ArrayList<>(List.of("banana", "kiwi", "grape", "melon"));

        // Remove duplicates from list1 that are in list2
        list1.removeAll(list2);

        // Remove duplicates from list2 that are in list1
        list2.removeAll(list1);

        System.out.println("List 1 after removing duplicates: " + list1);
        System.out.println("List 2 after removing duplicates: " + list2);
    }
}

합집합

List<String> uniqueList = new ArrayList<>(list1);
uniqueList.addAll(list2);
System.out.println("Combined unique list: " + uniqueList);