学习如何使用Collection.removeIf()、LinkedHashSet和Stream API从Java中的List中删除重复元素。
1.使用Collection.removeIf()
removeIf()方法会移除满足指定Predicate条件的此集合的所有元素。每个匹配的元素都是使用Iterator.remove()来移除的。如果集合的迭代器不支持删除操作,那么在第一个匹配元素上将抛出UnsupportedOperationException异常。
在下面的代码中,Predicate将当前元素添加到一个HashSet中。由于HashSet不允许重复项,对于它们,add()方法将返回false。所有这些重复项都从列表中删除,最终,列表只包含唯一项。

程序员导航
优网导航旗下整合全网优质开发资源,一站式IT编程学习与工具大全网站
List<Integer> items = new ArrayList<>(Arrays.asList(1, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8));
Set<Integer> set = new HashSet<>(items.size());
items.removeIf(p -> !set.add(p));
System.out.println(items); //[1, 2, 3, 4, 5, 6, 7, 8]
2.使用Stream.distinct()
我们可以使用Java 8的Stream.distinct()方法,该方法返回一个由对象的equals()方法比较的唯一元素组成的流。最后,使用Collectors.toList()将所有唯一元素收集为List。
ArrayList<Integer> numbersList = new ArrayList<>(Arrays.asList(1, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8));
List<Integer> listWithoutDuplicates = numbersList.stream().distinct().collect(Collectors.toList());
System.out.println(listWithoutDuplicates); //[1, 2, 3, 4, 5, 6, 7, 8]
3.使用LinkedHashSet
LinkedHashSet是另一种从ArrayList中删除重复元素的好方法。LinkedHashSet在内部执行两个操作:
- 删除重复元素
- 保持添加到其中的元素的顺序
在给定的示例中,ArrayList中的项目包含整数;其中一些是重复的数字,例如1、3和5。我们将列表添加到LinkedHashSet中,然后将内容再次获取到列表中。结果ArrayList不包含重复的整数。
ArrayList<Integer> numbersList = new ArrayList<>(Arrays.asList(1, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8));
LinkedHashSet<Integer> hashSet = new LinkedHashSet<>(items);
ArrayList<Integer> listWithoutDuplicates = new ArrayList<>(hashSet);
System.out.println(listWithoutDuplicates); //[1, 2, 3, 4, 5, 6, 7, 8]
如果您有关于如何从Java中的ArrayList中删除重复对象的问题,请随时留言。

AI 工具导航
优网导航旗下AI工具导航,精选全球千款优质 AI 工具集
© 版权声明
文章版权归作者所有,未经允许请勿转载。
相关文章
暂无评论...



