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

运行结果如下:

相关推荐
虾壳云官方7 分钟前
OpenClaw 2.7.9 Windows 一键部署教程:零基础也能搭建 AI 自动化助手
运维·人工智能·windows·自动化·openclaw·openclaw一键部署
xcLeigh2 小时前
鸿蒙平台 KeePass 密码管理器适配实战:从 Windows 到 鸿蒙PC 的 Electron 迁移指南
windows·electron·web·harmonyos·加密算法·keepass
垂钓的小鱼14 小时前
TRIZ理论是什么?萃智引擎如何将它变为工程师的AI创新助手
人工智能·microsoft
caimouse5 小时前
Reactos 第 9 章 设备驱动 — 9.1 Windows的设备驱动框架
windows
宸丶一5 小时前
Day 10:LangGraph - Agent 的图执行引擎
java·windows·python
ylscode6 小时前
GreatXML BitLocker绕过漏洞深度解析:Windows Defender离线扫描如何被改造成本地提权后门
windows·安全
caimouse7 小时前
Reactos 第 8 章 结构化异常处理 — 8.1 结构化异常处理的程序框架
windows
caimouse7 小时前
Reactos 第 7 章 视窗报文 — 7.1 视窗线程与 Win32k 扩充系统调用
windows
caimouse8 小时前
Reactos 第 9 章 设备驱动 — 9.7 一个过滤设备驱动模块的示例
windows
caimouse8 小时前
Reactos 第 7 章 视窗报文 — 7.7 鼠标器输入线程
windows