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);
   }

运行结果如下:

相关推荐
找方案1 小时前
北京砸1亿支持智能体:Agent创业迎来黄金窗口期
大数据·人工智能·microsoft
极地野狼 音乐哔哔1 小时前
[MAF预定义的AIContextProvider-03]ChatHistoryMemoryProvider——赋予Agent从经验中学习的能力
学习·microsoft
大模型码小白3 小时前
在 Windows 下 Codex 安装、配置与使用详细指南
java·人工智能·windows
小小龙学IT3 小时前
C++ Placement New 与显式析构:手动对象生命周期管理的艺术
c++·windows·mfc
luyun0202023 小时前
论坛里的小工具,吾爱出品
运维·服务器·windows
老王生涯5 小时前
rust开发环境配置-Windows & GNU
开发语言·windows·rust
nLif5 小时前
进程管道通讯-伪终端方式
c++·windows
梓仁沐白5 小时前
【Agent 设计模式】多智能体协作
microsoft·设计模式·php
CodexDave6 小时前
Python 自动化接单实战(九):Windows 免环境交付如何打包与诊断
windows·python·自动化·python自动化·pyinstaller·软件交付·windows打包
DB哥讲数据库6 小时前
【windows安装sql server教程】25步图文详解(附安装包)
windows