list删除重复元素几种思路

文章目录

list删除重复元素几种思路

hashset

java 复制代码
        List<String> list2 = new ArrayList<>();
        list2.add("a");
        list2.add("b");
        list2.add("a");
        Set<String> set = new HashSet<>(list2);
        for (String item : set) {
            log.info("[{}]",item);
        }
复制代码
23:29:46.093 [main] INFO com.geekmice.sbeasypoi.service.impl.ds - [a]
23:29:46.105 [main] INFO com.geekmice.sbeasypoi.service.impl.ds - [b]

Stream流

distinct()是Java 8 中 Stream 提供的方法,返回的是由该流中不同元素组成的流。distinct()使用 hashCode() 和 eqauls() 方法来获取不同的元素。

因此,需要去重的类必须实现 hashCode() 和 equals() 方法。换句话讲,我们可以通过重写定制的 hashCode() 和 equals() 方法来达到某些特殊需求的去重。

java 复制代码
 List<String> list2 = new ArrayList<>();
        list2.add("a");
        list2.add("b");
        list2.add("a");
 list2=list2.stream().distinct().collect(Collectors.toList());
 for (String item : list2) {
     log.info("元素:[{}]",item);
 }
bash 复制代码
23:31:49.434 [main] INFO com.geekmice.sbeasypoi.service.impl.ds - 元素:[a]
23:31:49.444 [main] INFO com.geekmice.sbeasypoi.service.impl.ds - 元素:[b]

删除所有重复元素

思想:其实就是获取非重复元素,将所有元素划分为重复元素和正常元素,用两个标志位说明,1表示正常元素,超过1

的都是累加出来,

java 复制代码
 List<String> list2 = new ArrayList<>();
        list2.add("a");
        list2.add("b");
        list2.add("a");
        Map<String, Integer> cachedMap = new HashMap<>(16);
        for (String item : list2) {
            Integer count = cachedMap.get(item);
            cachedMap.put(item, Objects.isNull(count) ? 0 : count + 1);
        }
        List<String> cachedList = new ArrayList(16);
        for (Map.Entry<String, Integer> integerEntry : cachedMap.entrySet()) {
            if (integerEntry.getValue() != 1) {
                cachedList.add(integerEntry.getKey());
            }
        }
        for (String content : cachedList) {
            log.info("非重复:[{}]", content);
        }
bash 复制代码
23:38:59.454 [main] INFO com.geekmice.sbeasypoi.service.impl.ds - 非重复:[b]
相关推荐
请你喝好果汁64110 分钟前
python_竞态条件
开发语言·python
正在走向自律12 分钟前
Python 数据分析与可视化:开启数据洞察之旅(5/10)
开发语言·人工智能·python·数据挖掘·数据分析
我来整一篇17 分钟前
用Redis的List实现消息队列
数据库·redis·list
dudly35 分钟前
Python 字典键 “三变一” 之谜
开发语言·python
小明.杨1 小时前
Django 中时区的理解
后端·python·django
陈奕昆2 小时前
五、【LLaMA-Factory实战】模型部署与监控:从实验室到生产的全链路实践
开发语言·人工智能·python·llama·大模型微调
程序猿小三2 小时前
python uv的了解与使用
开发语言·python·uv
T0uken2 小时前
【Python】UV:单脚本依赖管理
chrome·python·uv
郭逍遥2 小时前
[工具]B站缓存工具箱 (By 郭逍遥)
windows·python·缓存·工具
alpszero3 小时前
YOLO11解决方案之物体模糊探索
人工智能·python·opencv·计算机视觉·yolo11