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

运行结果如下:

相关推荐
宝桥南山8 小时前
Azure - 检查一下是否需要在Microsoft Extra ID中配置Passkeys认证方法
microsoft·微软·sass·azure
zhangfeng11339 小时前
2026-08-10/11 AI 领域重要动态筛选(侧重 AI coding 与具身智能)
人工智能·microsoft
for_ever_love__13 小时前
python基础语法学习: 数据容器
windows·python·学习
张赐荣14 小时前
Android TalkBack 无障碍优化: 为控件自定义转子导航动作
android·microsoft
huainingning14 小时前
微软windows系统官网IPV6临时地址介绍
windows·microsoft·智能路由器
一次旅行18 小时前
Agent面试题答案整理(一)
人工智能·microsoft
.Peter19 小时前
.NET/WPF 程序在部分 Windows 电脑无法保存用户环境变量:使用 DPAPI 实现安全兼容
windows·信息安全·c#·.net·wpf·环境变量·dpapi
码字的特恩19 小时前
微软确认暂不为 Windows 11 加入透明效果自定义功能,建议用户使用第三方工具
人工智能·windows·算法·microsoft·计算机·大模型·编程
神奇小梵20 小时前
安全和开发的需要了解的知识————下载内容的安全,和下载内容如何运行
android·windows·安全·个人开发
fchen52120 小时前
JSON:一站式开发者工具集,SQL日志解析并填充 、JSON格式化 与文本比对
sql·microsoft·json