java如何实现去重
使用HashSet去重
HashSet基于哈希表实现,自动去除重复元素。将集合或数组转换为HashSet即可去重。
List<String> list = Arrays.asList("a", "b", "a", "c");
Set<String> set = new HashSet<>(list); // 去重后的结果:["a", "b", "c"]
使用Stream API去重
Java 8及以上版本可用Stream的distinct()方法对集合去重。

List<String> list = Arrays.asList("a", "b", "a", "c");
List<String> distinctList = list.stream().distinct().collect(Collectors.toList());
// 结果:["a", "b", "c"]
使用TreeSet去重并排序
TreeSet基于红黑树实现,去重的同时按自然顺序或自定义比较器排序。
List<String> list = Arrays.asList("b", "a", "c", "a");
Set<String> set = new TreeSet<>(list); // 结果:["a", "b", "c"]
遍历手动去重
通过遍历原始集合,将不重复的元素添加到新集合中。

List<String> original = Arrays.asList("a", "b", "a", "c");
List<String> result = new ArrayList<>();
for (String item : original) {
if (!result.contains(item)) {
result.add(item);
}
}
// 结果:["a", "b", "c"]
使用LinkedHashSet保持插入顺序
LinkedHashSet去重的同时保留元素原始插入顺序。
List<String> list = Arrays.asList("b", "a", "c", "a");
Set<String> set = new LinkedHashSet<>(list); // 结果:["b", "a", "c"]
针对对象列表去重
若需根据对象属性去重,需重写equals()和hashCode(),或使用Stream自定义去重逻辑。
class Person {
private String name;
// 构造方法、getter/setter省略
@Override
public boolean equals(Object o) { /* 根据name判断相等性 */ }
@Override
public int hashCode() { /* 返回name的哈希值 */ }
}
List<Person> people = Arrays.asList(new Person("Alice"), new Person("Bob"), new Person("Alice"));
List<Person> distinctPeople = people.stream().distinct().collect(Collectors.toList());






