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

运行结果如下:

相关推荐
C++ 老炮儿的技术栈1 天前
Qt中自定义 QmyBattery 电池组件开发
c语言·开发语言·c++·windows·qt·idea·visual studio
驰羽1 天前
如何给Windows添加右键菜单选项
windows
石像鬼₧魂石1 天前
Windows 7 + Windows Server 2008 域环境渗透实战完整教程(详细版・教学专用)
windows
野生工程师1 天前
【Linux基础-2】Linux的基本指令
linux·运维·windows
玉梅小洋1 天前
C盘爆满 修改VS Code缓存与插件目录指定方法
开发语言·windows·visualstudio
dvlinker1 天前
使用 Bright Data 插件扩展 Microsoft TaskWeaver,实现网页数据高效获取
microsoft·taskweaver
billy_gisboy1 天前
02-Windows DockerDesktop部署ClickHouse,解决指定磁盘数据持久化问题与WSL2调优
windows·clickhouse
薛定谔的猫喵喵1 天前
【从零构建】PHP网络安全渗透测试靶场:5大基础漏洞实战
windows·sql·web安全·php
卡兰芙的微笑1 天前
GDB调试指南:从入门到精通
windows
优选资源分享1 天前
PowerToys v0.97.0 Windows 窗口优化 + 搜索工具
windows·实用工具