在 Java 中如何删除 ArrayList 中的重复元素

使用LinkedHashSet去除arraylist中的重复元素

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;
public class ArrayListExample 
{
    public static void main(String[] args) 
    {
        // ArrayList with duplicate elements
        ArrayList<Integer> numbersList = new ArrayList<>(Arrays.asList(1, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8));

        System.out.println(numbersList);
        LinkedHashSet<Integer> hashSet = new LinkedHashSet<>(numbersList);

        ArrayList<Integer> listWithoutDuplicates = new ArrayList<>(hashSet);

        System.out.println(listWithoutDuplicates);
    }
}

程序输出:

[1, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]
日期:2020-09-17 00:09:25 来源:oir作者:oir