示例 1: 使用 Set 从 ArrayList 中删除重复元素
import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.Set; class Main { public static void main(String[] args) { // create an arraylist from the array // using asList() method of the Arrays class ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 1, 3)); System.out.println("ArrayList with duplicate elements: " + numbers); // convert the arraylist into a set Set<Integer> set = new LinkedHashSet<>(); set.addAll(numbers); // delete al elements of arraylist numbers.clear(); // add element from set to arraylist numbers.addAll(set); System.out.println("ArrayList without duplicate elements: " + numbers); } }
输出
ArrayList with duplicate elements: [1, 2, 3, 4, 1, 3] ArrayList without duplicate elements: [1, 2, 3, 4]
在上面的例子中,我们创建了一个名为
numbers 的数组列表。数组列表包含重复元素。
要从数组列表中删除重复元素,我们有
将 arraylist 中的所有元素添加到 set
使用 clear()
方法清空数组列表
将集合中的所有元素添加到数组列表
这里,我们使用了
LinkedHashSet
来创建一个集合。这是因为它删除了重复元素并保持了插入顺序。要了解更多信息,请访问 Java LinkedHashSet。
示例 2: 使用 Stream 从 ArrayList 中删除重复元素
import java.util.ArrayList; import java.util.Arrays; import java.util.stream.Collectors; import java.util.stream.Stream; class Main { public static void main(String[] args) { // create an arraylist from the array // using asList() method of the Arrays class ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 1, 3)); System.out.println("ArrayList with duplicate elements: " + numbers); // create a stream from arraylist Stream<Integer> stream = numbers.stream(); // call the distinct() of Stream // to remove duplicate elements stream = stream.distinct(); // convert the stream to arraylist numbers = (ArrayList<Integer>)stream.collect(Collectors.toList()); System.out.println("ArrayList without duplicate elements: " + numbers); } }
输出
ArrayList with duplicate elements: [1, 2, 3, 4, 1, 3] ArrayList without duplicate elements: [1, 2, 3, 4]
在上面的例子中,我们创建了一个名为
numbers 的数组列表。数组列表包含重复元素。
这里,我们使用了 Stream 类从数组列表中删除重复元素。
numbers.stream()-从数组列表创建一个流
stream.distinct()-删除重复元素
stream.collect(Collectors.toList())-从流中返回一个列表
这里,我们使用类型转换将返回的列表转换为数组列表。