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

运行结果如下:

相关推荐
蓝鸟19741 小时前
Windows Route 内外网双通原理+实战详解(彻底解决双网卡互斥断网)
windows·网络运维·电脑网络配置·路由冲突解决·route命令·内外网同时上网·windows路由 双网卡双通
2601_961845422 小时前
法考真题及答案解析|历年真题|资料已整理
linux·windows·ubuntu·macos·centos·gnu
小黄人软件3 小时前
Claude和Codex下载离线包 安装遇到问题:windows无法访问指定设备 路径 文件 应用无法打开也无法卸载,解决了
人工智能·microsoft·openai·codex
coolwaterld3 小时前
windows下删文件,找出“到底是谁占用
windows
caimouse5 小时前
Reactos 第6章 进程间通信(续)
windows
触底反弹6 小时前
拷个 .exe 到新电脑就跑不起来?你缺的不是文件,是对链接的理解
c++·windows·操作系统
W优化大师6 小时前
Windows 更新待处理弹窗一直不消失怎么解决,C 盘空间和后台任务该如何排查
windows·系统优化·磁盘清理·windows11·c盘·系统更新
golfscript6 小时前
Playwright Python:微软出的浏览器自动化库
python·其他·microsoft·自动化
无风听海6 小时前
在 ASP.NET Core 开发环境中为自定义域名签发受信任的自签名证书—HSTS 启用后的完整实践
windows·后端·asp.net
Ztopcloud极拓云视角7 小时前
我用AI辅助做了一个多端工具:解决2026世界杯回放被剧透的问题
人工智能·windows·个人开发