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]
相关推荐
Gabriel Drop Out9 分钟前
10年408考研真题-数据结构
数据结构·考研
爱看书的小沐16 分钟前
【小沐学GIS】blender导入OpenStreetMap城市建筑(blender-osm、blosm)
python·gis·blender·openstreetmap·osm·blosm·blender-osm
算法萌新——117 分钟前
洛谷P5740——结构体运用
数据结构·算法·图论
细节的温柔34 分钟前
Python的主要特点及其应用领域
开发语言·python
IT规划师1 小时前
数据结构与算法之间有何关系?
数据结构·算法
Xiu Yan1 小时前
LeetcodeTop100 刷题总结(一)
java·数据结构·算法·链表·矩阵·哈希算法·数组
彤银浦1 小时前
Python学习过程记录1
python·学习
学步_技术1 小时前
Python编码系列—Python代理模式:为对象赋予超能力的魔法
开发语言·python·代理模式
鱼跃鹰飞1 小时前
Leetcode面试经典150题-198.打家劫舍
数据结构·算法·leetcode·面试·职场和发展
Midsummer啦啦啦2 小时前
网址匹配正则表达式(python实现)
开发语言·python·正则表达式