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

运行结果如下:

相关推荐
凌镜icecraft3 小时前
我改文件扩展名的时候那个警告弹窗再也不会弹出来了
windows·c#·wpf·explorer
the3clipse7 小时前
Windows 11 26H2 AI 功能使用指南:回顾、单击以执行与实时字幕
人工智能·windows·copilot+ pc·recall 回顾·单击以执行·实时字幕翻译·windows studio
the3clipse12 小时前
Windows 11 26H2 账户登录与 Windows Hello 指南:并行验证、增强登录安全与无密码设置
windows·无密码登录·windows hello·增强登录安全性ess·pin与密码区别·动态锁·win11 26h2
承渊政道12 小时前
Toonflow AI短剧教程:Windows部署、批量生成与角色一致性
人工智能·windows·cpolar·ai短剧·toonflow
钱栈up16 小时前
微软商店把《我的世界》国区从 89 涨到 110.99:一个「小调价」里的平台定价权博弈
游戏·microsoft·raft
Summer-Bright2 天前
深度 | 决策模型抢滩:OpenAI 微软同周下场,大模型从生成文本转向输出概率判断
人工智能·microsoft·ai·微软·qwen·决策
柳鲲鹏3 天前
编译Windows版本的zlib
windows
Name_NaN_None3 天前
安卓手机远程控制电脑方法(Android/Windows) —— 「小白教程」
android·windows·智能手机·电脑·笔记本
En^_^Joy3 天前
LangChain消息系统全解析:从基础到实战(四)
数据库·microsoft·langchain
宝桥南山3 天前
Visual Studio - 记录一个Visual Studio 2026(Insiders)的更新问题
windows·microsoft·微软·.net·.netcore·visual studio