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]
相关推荐
XYN613 分钟前
【嵌入式学习3】基于python的tcp客户端、服务器
服务器·开发语言·网络·笔记·python·学习·tcp/ip
一一代码10 分钟前
ide技术
ide·python
No0d1es16 分钟前
CCF GESP Python编程 三级认证真题 2025年3月
python·青少年编程·gesp·ccf·三级
JobDocLS25 分钟前
深度学习环境安装
python
二狗哈1 小时前
go游戏后端开发24:写完赢三张游戏
python·游戏·golang
明月看潮生1 小时前
青少年编程与数学 02-016 Python数据结构与算法 03课题、数组与链表
数据结构·python·青少年编程·编程与数学
niuniu_6662 小时前
针对 Python 3.7.0,以下是 Selenium 版本的兼容性建议和安装步骤
开发语言·chrome·python·selenium·测试工具
苏卫苏卫苏卫2 小时前
【Python】数据结构练习
开发语言·数据结构·笔记·python·numpy·pandas
DexterLien2 小时前
Flask + Pear Admin Layui 快速开发管理后台
python·flask·layui
码界筑梦坊2 小时前
基于Flask的笔记本电脑数据可视化分析系统
python·信息可视化·flask·毕业设计·电脑