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

运行结果如下:

相关推荐
承渊政道3 小时前
Python IDLE鸿蒙PC适配全记录:用 ArkUI 重建编辑、运行、Shell 与基础调试闭环
python·microsoft·harmonyos·鸿蒙系统·pc端
StarDream-Online3 小时前
Windows 下 uv 安装与配置完全指南(含环境变量设置)
windows·uv
啾啾Fun4 小时前
【AI Coding】5-Pi Agent Harness:一个极简终端编码Harness的解构
人工智能·microsoft·ai agent·claude code·ai coding
空 白II4 小时前
cuda toolkit 10.0 windows 安装实录
windows
名字还没想好☜4 小时前
Java Collectors.groupingBy 进阶:多级分组、下游收集器与统计聚合一次搞定
java·windows·后端·python·spring
漂着的圆木5 小时前
模型应用Gemini登陆Windows:Alt+Space唤起
windows
csdn_aspnet5 小时前
如何从电脑主机拷东西到VWmare虚拟机
linux·运维·服务器·windows·vmware·虚拟机
艺杯羹7 小时前
告别碎片化ToolCall:Model Context Protocol (MCP) 核心机理与私有数据总线落地实战
人工智能·microsoft·系统架构·大模型·mcp
Li Ming&16 小时前
Windows Server 2019 操作系统《保姆级安装教程》
windows·信息与通信
陈天伟教授18 小时前
Windows操作技巧 -03
windows