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 小时前
ROS2进阶:服务通信、自定义SRV接口、参数服务器与基于服务的参数通信详解
java·开发语言·microsoft
爱吃火鸡面呀6 小时前
Spark RDD 行动算子(Action)详解
windows·ajax·spark
dlhto6 小时前
Windows 使用 Rufus 制作 AlmaLinux 10.2 启动 U 盘:从 ISO 下载到服务器安装
运维·服务器·windows
小矮强7 小时前
输入凭证也没用?Windows 共享文件夹“来宾访问被安全策略阻止”
windows·经验分享
不爱学英文的码字机器7 小时前
从Q1迁到T1,同一个编号已经换了含义
前端·数据库·microsoft
青春不朽5127 小时前
Python 的 list append 为什么是均摊 O(1)?拆开过度分配那张表,看容量翻倍背后的暗账
java·python·list
skywalk81637 小时前
Virtualbox 从7.2.20降级到7.2.18 @FreeBSD系统
windows·virtualbox·freebsd
龙亘川7 小时前
城市公共安全治理如何从“人海战术“走向“数据驱动“?
大数据·数据库·人工智能·安全·microsoft·智慧城市·数据可视化
DogDaoDao7 小时前
Windows 双 Shell 全面对比:CMD 与 PowerShell 的技术剖析
windows·shell·测试·powershell·cmd·程序员开发
长不大的杨瑞杰8 小时前
Windows 安装 OpenCode v2:原生、WSL、Desktop 怎么选?完整配置与避坑指南
人工智能·windows·ai agent·opencode