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

运行结果如下:

相关推荐
江畔柳前堤2 小时前
HBM:大语言模型时代的「算力血液」——从内存墙到带宽革命的深度拆解
服务器·人工智能·windows·目标检测·语言模型·自然语言处理·软件工程
冬奇Lab4 小时前
开源项目第183期:Ontology Playground — 微软出品的本体论可视化学习工具,零后端、浏览器直接运行
人工智能·microsoft·开源
意图共鸣4 小时前
意图共鸣科技8月10日正式发布《AI协作记忆系统 · 认知架构白皮书》
人工智能·科技·microsoft
天天进步20156 小时前
UI-TARS 源码解析 #22:二次开发实战:用 UI-TARS 做一个简单的 Windows 自动操作 Agent
windows·ui
啊哈一半醒6 小时前
Windows 虚拟机搭建 CentOS 全过程(2026 最新版 + 踩坑解决)
linux·windows·centos
new_zhou7 小时前
C++ 项目 AI 协作指南(Windows / MSVC 环境)
c++·人工智能·windows
蔬菜_7 小时前
前端转全栈-day5(数组、list、set)
java·前端·数据结构·list
爬楼的猪10 小时前
跟着AI Agent学powershell
windows·ai编程
笨鸟先飞,勤能补拙10 小时前
网络安全等级保护 2.0:从定级备案、建设整改到持续合规的系统指南
网络·人工智能·windows·安全·web安全·网络安全·github
yagami_gagami11 小时前
2026平航杯内存取证(StarMem)
windows·网络安全