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

运行结果如下:

相关推荐
剪刀石头布Cheers8 小时前
NDM浏览器插件无法连接后台的问题
windows·端口冲突·ndm
hkj880812 小时前
Linux 总线-设备-驱动(Bus-Device-Driver)完整协作原理
linux·运维·microsoft
PiaoShiSun13 小时前
Windows环境下批量删除文件夹内仅有1个/2个/*个文件的文件夹
windows·批量删除单文件的文件夹
足球中国14 小时前
nuget把缓存搬离C盘
c语言·windows·缓存
love530love16 小时前
ComfyUI 插件发布 GitHub Release + Comfy Registry (官方节点商店)完整复盘教程(从零开始)
人工智能·windows·github·devops
ofoxcoding16 小时前
Windows 上 Codex 报 “failed to start codex app-server“:成因与修复(2026)
windows·ai
liuyukuan17 小时前
C盘清理之Windows.db
windows·c盘红了
每天都进步一点点17 小时前
Windows 系统安装 Python 3.11+ 详细教程
windows·python3.11
facaixxx202417 小时前
AI模型的Function Calling能力:工作原理及模型支持清单
microsoft
开发小程序的之朴19 小时前
安企CMS的安装-PHPStudy(小皮面板)部署
windows·mysql·nginx