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]
相关推荐
硬件人某某某1 分钟前
基于Django的手办交易平台~源码
后端·python·django
升讯威在线客服系统13 分钟前
如何通过 Docker 在没有域名的情况下快速上线客服系统
java·运维·前端·python·docker·容器·.net
久绊A2 小时前
Python 基本语法的详细解释
开发语言·windows·python
Hylan_J6 小时前
【VSCode】MicroPython环境配置
ide·vscode·python·编辑器
莫忘初心丶6 小时前
在 Ubuntu 22 上使用 Gunicorn 启动 Flask 应用程序
python·ubuntu·flask·gunicorn
失败尽常态5239 小时前
用Python实现Excel数据同步到飞书文档
python·excel·飞书
2501_904447749 小时前
OPPO发布新型折叠屏手机 起售价8999
python·智能手机·django·virtualenv·pygame
青龙小码农9 小时前
yum报错:bash: /usr/bin/yum: /usr/bin/python: 坏的解释器:没有那个文件或目录
开发语言·python·bash·liunx
大数据追光猿9 小时前
Python应用算法之贪心算法理解和实践
大数据·开发语言·人工智能·python·深度学习·算法·贪心算法
夏末秋也凉9 小时前
力扣-回溯-46 全排列
数据结构·算法·leetcode