Java中HashSet去重需重写equals和hashCode;基础类型可直接用new HashSet(list)转List,但无序;保持顺序用LinkedHashSet;自定义对象必须重写两方法;Stream.distinct()更简洁。

Java 中用 HashSet 对 List 去重,核心是利用 HashSet 不允许重复元素的特性,将 List 元素全部添加进去,再转回 List。这种方式简洁高效,但要注意元素必须正确重写 equals() 和 hashCode() 方法(对自定义对象尤其关键)。
基础类型或 String 的快速去重
对于 String、Integer、Long 等已重写 equals 和 hashCode 的类型,可直接构造 HashSet:
- 创建新
HashSet,传入原List构造器,自动去重 - 再用
new ArrayList(set)转为新List
示例代码:
List<String> list = Arrays.asList("a", "b", "a", "c", "b");
Set<String> set = new HashSet<>(list);
List<String> uniqueList = new ArrayList<>(set);
⚠️注意:顺序不保证,因为 HashSet 无序。如需保持插入顺序,改用 LinkedHashSet。
立即学习“Java免费学习笔记(深入)”;
保持原有顺序的去重(推荐常用)
用 LinkedHashSet 替代 HashSet,它既去重,又按首次插入顺序保存元素:
-
new LinkedHashSet<>(list)自动跳过重复项,且保留第一次出现的位置顺序 - 再转成
ArrayList即可获得有序无重复列表
示例:
List<String> list = Arrays.asList("x", "y", "x", "z", "y");
List<String> uniqueList = new ArrayList<>(new LinkedHashSet<>(list));
// 结果:["x", "y", "z"]
自定义对象去重的关键点
若 List<User> 中有重复对象,仅靠 HashSet 不会生效,除非你做了以下两件事:
- 在
User类中重写equals(Object o)方法,明确“两个对象相等”的逻辑(比如 id 相同即相等) - 同步重写
hashCode()方法,确保equals返回true的对象,其hashCode值也相同 - 建议用 IDE(如 IntelliJ)自动生成这两个方法,避免手动出错
否则,默认使用继承自 Object 的 equals(比较内存地址),所有对象都被视为不同。
一行流式写法(Java 8+)
借助 Stream API 可更函数式地实现:
list.stream().distinct().collect(Collectors.toList())- 底层也是依赖
equals+hashCode,语义清晰,适合链式调用场景 - 性能与
LinkedHashSet方式接近,可读性更好
示例:
List<Integer> nums = Arrays.asList(1, 2, 2, 3, 1); List<Integer> unique = nums.stream().distinct().collect(Collectors.toList());


















