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

运行结果如下:

相关推荐
Mr.亮先生13 小时前
# 把 DeepSeek 官方 Agent 工作台,直接装进 Windows 启动器里
windows·deepseek·harness
曹牧18 小时前
C#:List<string>特定格式输出
windows·c#
易点云徐源20 小时前
(已解决)Photoshop 多画板 Alt+拖动复制随机卡死 4~5 分钟
windows·photoshop
Dovis(誓平步青云)20 小时前
DevEco Studio 6.1.1 Windows 安装实录:从下载校验到首次启动
android·开发语言·数据库·人工智能·windows·harmonyos
bosins20 小时前
将 Hyper-V 上的 Ubuntu 虚拟机内容迁移到 WSL (Windows Subsystem for Linux) 中
linux·windows·ubuntu
海盗12341 天前
微软技术周报 · 2026-08-11~2026-08-18
人工智能·microsoft·.net
ι:1 天前
DeepSeek Harness 桌面一键启动与网页背景修改指南
windows·学习·deepseekharness
zuozewei1 天前
7DGroup 开源 dsh-7d-tray-win 系统托盘插件
windows·代码复审
深念Y1 天前
Wine 运行 HiTool 踩坑记录
linux·windows·容器·桌面·wine·虚拟器
玖釉-1 天前
nvpro_core2 源码与架构解析:NVIDIA Vulkan 图形开发基础框架
c++·windows·图形渲染