How to eliminate duplicate elements from an ArrayList in Java?

You can use a HashSet to remove duplicate elements from an ArrayList. HashSet automatically removes duplicate elements.

Here is a sample code:

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

public class RemoveDuplicates {
    public static void main(String[] args) {
        ArrayList<Integer> listWithDuplicates = new ArrayList<>();
        listWithDuplicates.add(1);
        listWithDuplicates.add(2);
        listWithDuplicates.add(3);
        listWithDuplicates.add(2);
        listWithDuplicates.add(1);
        
        // 使用HashSet去掉重复元素
        HashSet<Integer> setWithoutDuplicates = new HashSet<>(listWithDuplicates);
        
        // 将去重后的元素重新放回ArrayList
        ArrayList<Integer> listWithoutDuplicates = new ArrayList<>(setWithoutDuplicates);
        
        // 输出去重后的ArrayList
        for (Integer number : listWithoutDuplicates) {
            System.out.println(number);
        }
    }
}

Output result:

1
2
3
Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds