使用LinkedHashSet数据类型是最简单的去除ArrayList重复元素的方法。有点类似python里的set数据类型。上代码
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]
方法摘自:https://howtodoinjava.com/java/collections/arraylist/remove-duplicate-elements/