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 小时前
ClaudeCode搭配DeepSeek在Windows和Linux中的安装教程
linux·运维·windows
瀚高PG实验室18 小时前
SQL优化案例:使用分区表优化SQL查询性能
linux·服务器·数据库·sql·microsoft·postgresql
WA内核拾荒者20 小时前
WhatsApp账号运营SOP的可视化编排与流水线监控
大数据·数据库·windows
Java小白笔记1 天前
Windows系统免软件命令激活
java·网络·人工智能·windows·ai·ai编程
IT小盘1 天前
17-AI应用防止越权访问知识库
服务器·网络·windows
rust&python1 天前
通达信量化tdxquant快速开始第一个策略
windows·量化·通达信·tdxquant
编码者卢布1 天前
【Azure Key Vault】资源组被误删后,如何恢复 Azure Key Vault?
microsoft·flask·azure
Albart5751 天前
Windows快速访问幽灵文件夹彻底解决|清除tmp残留_无效固定项_侧边栏残留(Win10_Win11通用)
windows·powershell脚本·快速访问修复·幽灵文件夹清理·tmp垃圾清除·电脑系统优化
clorinda1 天前
把 DeepSeek Harness 打包成类似 Codex 的 Windows 桌面应用:Electron、一键启动、插件管理和动态壁纸
前端·javascript·windows·electron
2401_869769591 天前
list 2
数据结构·list