数组和列表去重方法:数组去重:使用 Set 转换或 ArrayList 转 Set 再转数组。列表去重:使用 LinkedHashSet 保留插入顺序或使用 Set 转换或 ArrayList 转 Set 再转 ArrayList。

Java 数组和列表去重
数组去重
- 使用 Set 转换:将数组转换为 Set 集合,它自动过滤重复元素。
int[] arr = {1, 2, 3, 4, 5, 1, 2};
Set uniqueSet = new HashSet<>(Arrays.asList(arr)); - 使用 ArrayList 转 Set 再转数组:与 Set 转换类似,使用 ArrayList 作为中间步骤。
int[] arr = {1, 2, 3, 4, 5, 1, 2};
List uniqueList = new ArrayList<>(Arrays.asList(arr));
int[] uniqueArray = uniqueList.stream().distinct().toArray(); 列表去重
- 使用 LinkedHashSet:将列表转化为 LinkedHashSet 保留插入顺序,然后转回 ArrayList。
Listlist = Arrays.asList(1, 2, 3, 4, 5, 1, 2); LinkedHashSet uniqueSet = new LinkedHashSet<>(list); List uniqueList = new ArrayList<>(uniqueSet);
- 使用 Set 转换:与数组去重类似,将列表转换为 Set。
Listlist = Arrays.asList(1, 2, 3, 4, 5, 1, 2); Set uniqueSet = new HashSet<>(list); List uniqueList = new ArrayList<>(uniqueSet);
- 使用 ArrayList 转 Set 再转 ArrayList:与数组去重类似,使用 ArrayList 作为中间步骤。
Listlist = Arrays.asList(1, 2, 3, 4, 5, 1, 2); List uniqueList = new ArrayList<>(); for (Integer num : list) { if (!uniqueList.contains(num)) { uniqueList.add(num); } }











