使用LinkedHashSet删除数组中的重复项
我们将数组中的所有元素添加到 LinkedHashSet
中,然后我们将把 linkshashSet 转换为数组。
import java.util.Arrays; import java.util.LinkedHashSet; public class RemoveDuplicateExample { public static void main(String[] args) throws CloneNotSupportedException { // 原始数组包含重复值 Integer[] numbers = new Integer[] {1,2,3,4,5,1,3,5}; System.out.println( Arrays.toString(numbers) ); // 创建一个set LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<>( Arrays.asList(numbers) ); // 转换为数组 Integer[] numbersWithoutDuplicates = linkedHashSet.toArray(new Integer[] {}); System.out.println( Arrays.toString(numbersWithoutDuplicates) ); } }
程序输出。
[1, 2, 3, 4, 5, 1, 3, 5] [1, 2, 3, 4, 5]
日期:2020-09-17 00:09:25 来源:oir作者:oir