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

运行结果如下:

相关推荐
邮专薛之谦3 小时前
Kotlin 全知识点复习+详细梳理
windows·kotlin·android studio·idea
自动化代码美学3 小时前
【Python3.13】官网学习之控制流
开发语言·windows·python·学习
q***33378 小时前
新版 WSL2 2.0 设置 Windows 和 WSL 镜像网络教程
windows
JasonSJX10 小时前
海海软件成为微软 PlayReady DRM 官方合作伙伴
microsoft·drm·视频加密·playready·数字版权保护
西焱44010 小时前
微软官方直链下载(winxp,win8,win10,win11镜像下载)
microsoft
季春二九10 小时前
微软 .Net 运行库丨多语言丨离线全集丨静默安装丨多架构支持
microsoft·.net
云泽80811 小时前
C++ List 容器详解:迭代器失效、排序与高效操作
开发语言·c++·list
xlq2232211 小时前
15.list(上)
数据结构·c++·list
Elastic 中国社区官方博客11 小时前
Elasticsearch:Microsoft Azure AI Foundry Agent Service 中用于提供可靠信息和编排的上下文引擎
大数据·人工智能·elasticsearch·microsoft·搜索引擎·全文检索·azure
未来之窗软件服务13 小时前
幽冥大陆(二十二)dark语言智慧农业电子秤读取——东方仙盟炼气期
开发语言·windows·golang·东方仙盟·东方仙盟sdk