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

运行结果如下:

相关推荐
caimouse12 分钟前
Reactos 第 5 章 进程与线程 — 5.8 Windows 的 APC 机制
c语言·windows
PHP隔壁老王邻居44 分钟前
windows菜单搜索栏无法显示历史记录或者无法使用修复方法
windows
道一231 小时前
Windows系统查看端口占用进程的3种实用方法
windows·笔记
半条-咸鱼1 小时前
【INACCESSIBLE_BOOT_DEVICE】安装 Config Tool 后 Windows 蓝屏,最终通过 VMware 虚拟机解决
windows·stm32·vmware·芯片
人工小情绪2 小时前
Windows 安装 Codex 桌面版,并用 CC Switch 管理配置
人工智能·windows·codex·cc switch
caimouse4 小时前
Reactos 第 5 章 进程与线程 — 5.11 线程本地存储 TLS
c语言·windows
李小白665 小时前
第二天-认识Windows
windows
liu6449113376 小时前
claude code 安装
windows
caimouse6 小时前
Reactos 第 5 章 进程与线程 — 5.9 Windows 线程的调度和切换
windows
骑士雄师6 小时前
17.2 通过 Config 传入用户名 → 工具1存入 State → 工具2读取 State 并返回答案
服务器·windows·microsoft