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

运行结果如下:

相关推荐
女神下凡1 小时前
PERSONAL.XLSB打开后,为什么在打开XLSX文件为什么会提示要 只读 打开
microsoft
海 月1 小时前
adb install 右键快捷菜单
windows
rosemary5121 小时前
Windows vscode Claude Code + DeepSeek V4
ide·windows·vscode·claude code·deepseek-v4-pro
2601_961194021 小时前
化学教资科三真题答案
linux·windows·ubuntu·pdf·centos·gnu
Fly feng2 小时前
windows pnp/power status Manager(设备 电源状态介绍)
windows·pnp/power
元Y亨H2 小时前
Windows蓝屏错误0x00000124 (硬件错误) 完整排查笔记
windows
小鹿软件办公2 小时前
微软发布旗下首款具备思考能力的 MAI-Thinking-1 AI 模型
人工智能·microsoft·语音识别
曲幽2 小时前
你的FastAPI又在服务器上“跑不起来”了?来,今天咱把打包这件事彻底聊透
linux·windows·python·docker·fastapi·web·pyinstaller·nssm·services
SEO-狼术2 小时前
Microsoft Announces Availability
microsoft
_可乐无糖3 小时前
踩完坑之后的总结:Windows安装docker
运维·windows·docker·容器