List 去重两种方式:stream(需要JDK1.8及以上)、HashSet

1、使用Stream 方法 使用JDK1.8及以上
复制代码
  /**
     * Java合并两个List并去掉重复项的几种做法
     * @param args
     */
    public static void main(String[] args) {

        String[] str1 = {"1", "2", "3", "4", "5", "6"};
        List<String> list1 = new ArrayList<>(Arrays.asList(str1));

        String[] str2 = {"4", "5", "8", "10", "3"};
        List<String> list2= new ArrayList<>(Arrays.asList(str2));
        // 去重信息
        List<String> collect= Stream.of(list1,list2)
                .flatMap(Collection::stream)
                .distinct()
                .collect(Collectors.toList());
        for (String str:collect) {
           log.info("测试结果:"+str);
        }
}

运行结果如下:

2、HashSet集合的方式进行去重

复制代码
      /**
     * Java合并两个List并去掉重复项的几种做法
     * @param args
     */
    public static void main(String[] args) {
        String[] str1 = {"1", "2", "3", "4", "5", "6"};
        List<String> list1 = new ArrayList<>(Arrays.asList(str1));

        String[] str2 = {"4", "5", "8", "10", "3"};
       log.info("=====================HashSet去重操作======================");
        Set<String> set = new HashSet<>(list1);
        set.addAll(list2);
        List<String> list = new ArrayList<>(set);
        log.info("hashSet去重:"+list);
   }

运行结果如下:

相关推荐
Trouvaille ~6 分钟前
【Redis篇】List 列表:双端队列与消息队列的完美实现
数据库·redis·list·双端队列·后端开发·quicklist·zoplist
Cheng小攸11 分钟前
CTF攻防综合实战(1)
windows
未力忘1 小时前
【无标题】
windows
大明者省1 小时前
在 Windows Server 2019 环境下配置 IIS 站点、本地端口服务、反向代理及内外网访问、多站点多服务部署
windows
您^_^1 小时前
ClaudeCode最近更新导致第三方模型Token消耗率暴涨,缓存命中也相当夸张!!
人工智能·windows·缓存·个人开发·claudecode·deepseek v4 pro
您^_^1 小时前
新手上路(四):Codex MCP 实战——让 Codex 连接外部世界
人工智能·windows·个人开发·codex·deepseek v4 pro
开开心心就好1 小时前
小白友好的程序联网封锁实用工具
windows·eureka·计算机外设·rabbitmq·word·excel·csdn开发云
MageGojo1 小时前
小程序每日一谜怎么做:riddle 接口接入示例
windows·小程序·apache·谜语
Dfreedom.10 小时前
Windows、虚拟机、开发板组网通信原理及调试通联步骤
人工智能·windows·部署·边缘计算·开发板·模型加速
三无推导15 小时前
ComfyUI 安装部署教程:Windows 下快速搭建可视化 AI 绘图工作流,零基础也能跑通
人工智能·pytorch·windows·stable diffusion·aigc·ai绘画·持续部署