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

运行结果如下:

相关推荐
ylscode1 小时前
微软推送KB5095189:Windows 11 OOBE开箱即用体验迎来新一轮优化
windows·microsoft
忧虑的小蚂蚁3 小时前
dll文件32位64位检测工具以及Windows文件夹SysWow64的坑
windows
千逐683 小时前
Uniapp 鸿蒙实战之 AtomGit APP - 仓库详情与文件树浏览
服务器·microsoft·uni-app
‿hhh4 小时前
Dify核心模块详解:从文本生成到智能体
人工智能·学习·microsoft·agent·上下文·记忆
杨云龙UP5 小时前
Windows SQL Server 备份无法传输至异地共享目录排查处理
运维·服务器·数据库·windows·共享·smb·异地备份传输
AI行业学习5 小时前
Notepad++ 官方纯净下载+完整安装教程(Windows)【2026.7.5】
开发语言·windows·python·前端框架·html·notepad++
站在墙头上5 小时前
Windows下安装 龙虾-Openclaw
windows·ai·openclaw
USC-XiangLuXun6 小时前
GUI软件灰盒测试技术和方法 篇一
功能测试·microsoft·集成测试·mfc
Data_Journal7 小时前
使用 Selenium 进行网页抓取:分步指南
selenium·测试工具·microsoft
骑士雄师7 小时前
大模型:MessagesPlaceholder 是什么?
服务器·windows·microsoft