行业资讯 2025年08月6日
0 收藏 0 点赞 257 浏览 1470 个字
摘要 :

文章目录 1.使用Collection.removeIf() 2.使用Stream.distinct() 3.使用LinkedHashSet 学习如何使用Collection.removeIf()、LinkedHashSet和Stream API从Java中的List……




  • 1.使用Collection.removeIf()
  • 2.使用Stream.distinct()
  • 3.使用LinkedHashSet

学习如何使用Collection.removeIf()、LinkedHashSet和Stream API从Java中的List中删除重复元素。

1.使用Collection.removeIf()

removeIf()方法会移除满足指定Predicate条件的此集合的所有元素。每个匹配的元素都是使用Iterator.remove()来移除的。如果集合的迭代器不支持删除操作,那么在第一个匹配元素上将抛出UnsupportedOperationException异常。

在下面的代码中,Predicate将当前元素添加到一个HashSet中。由于HashSet不允许重复项,对于它们,add()方法将返回false。所有这些重复项都从列表中删除,最终,列表只包含唯一项。

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中删除重复对象的问题,请随时留言。

微信扫一扫

支付宝扫一扫

版权: 转载请注明出处:https://www.zuozi.net/9315.html

管理员

相关推荐
2025-08-06

文章目录 一、Reader 接口概述 1.1 什么是 Reader 接口? 1.2 Reader 与 InputStream 的区别 1.3 …

985
2025-08-06

文章目录 一、事件溯源 (一)核心概念 (二)Kafka与Golang的优势 (三)完整代码实现 二、命令…

463
2025-08-06

文章目录 一、证明GC期间执行native函数的线程仍在运行 二、native线程操作Java对象的影响及处理方…

347
2025-08-06

文章目录 一、事务基础概念 二、MyBatis事务管理机制 (一)JDBC原生事务管理(JdbcTransaction)…

455
2025-08-06

文章目录 一、SnowFlake算法核心原理 二、SnowFlake算法工作流程详解 三、SnowFlake算法的Java代码…

515
2025-08-06

文章目录 一、本地Jar包的加载操作 二、本地Class的加载方法 三、远程Jar包的加载方式 你知道Groo…

831
发表评论
暂无评论

还没有评论呢,快来抢沙发~

助力内容变现

将您的收入提升到一个新的水平

点击联系客服

在线时间:08:00-23:00

客服QQ

122325244

客服电话

400-888-8888

客服邮箱

122325244@qq.com

扫描二维码

关注微信客服号