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]
相关推荐
程序员三藏14 分钟前
Selenium+python自动化测试:解决无法启动IE浏览器及报错问题
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
瓦尔登湖50830 分钟前
DAY 40 训练和测试的规范写法
python
站大爷IP1 小时前
Python中None与NoneType的真相:从单例对象到类型系统的深度解析
python
秋难降1 小时前
LRU缓存算法(最近最少使用算法)——工业界缓存淘汰策略的 “默认选择”
数据结构·python·算法
站大爷IP1 小时前
Python新手踩坑实录:这些错误你可能正在犯
python
我星期八休息1 小时前
大模型 + 垂直场景:搜索/推荐/营销/客服领域开发新范式与技术实践
大数据·人工智能·python
深盾安全1 小时前
uv,下一代Python包管理工具
python
山烛2 小时前
OpenCV 图像处理基础操作指南(二)
人工智能·python·opencv·计算机视觉
跟橙姐学代码2 小时前
学Python,先把这“三板斧”练到炉火纯青!(零基础也能看懂)
前端·python
让心淡泊1443 小时前
DAY 50 预训练模型+CBAM模块
python