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

运行结果如下:

相关推荐
影寂ldy1 小时前
C# 索引器(Indexer)超全笔记【基础 + 重载 + 实战练习】
windows·microsoft
带娃的IT创业者3 小时前
穿越回 1980:解读微软开源的“最早 DOS 源码”与操作系统的原点
microsoft·微软·开源·操作系统·dos·源码解析·计算机历史
caimouse4 小时前
Reactos 第 4 章 对象管理 — 4.2 对象类型(Object Type)
c语言·windows·架构
caimouse5 小时前
Reactos 第 4 章 对象管理 — 4.4 对象的创建
windows·架构
Chase_______5 小时前
【Java基础 | 16】集合框架(下):Map、HashMap 与 TreeMap
java·windows
San813_LDD5 小时前
[操作系统]虚拟机技术
linux·windows
阿昭L6 小时前
Windows堆管理
windows
caimouse6 小时前
Reactos 第 3 章 内存管理 — 【下篇】换出、Section、池
c语言·开发语言·windows·架构
Linlingu6 小时前
OpenClaw对接飞书机器人完整配置教程(长连接模式)
windows·机器人·飞书·办公自动化·数字员工·小龙虾
资源分享助手6 小时前
PeekDesktop:实现类似 macOS Sonoma 点击桌面预览(Windows工具教程)
windows·macos·点击回到桌面