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

运行结果如下:

相关推荐
sudebao点com12 小时前
一次“Google 能打开,FlexTV 打不开”的 DNS 故障排查:从 curl 超时到完整证据链
windows·macos·https·cdn·dns·nslookup·网络排错
非凡ghost14 小时前
分区助手:Windows 磁盘管理的“瑞士军刀“,分区调整不再怕丢数据
服务器·windows·电脑·软件需求
淡海水19 小时前
01-07-运行时-GC深度剖析-内存分配回收与结构选择
jvm·windows·unity·gc
DAVIED921 小时前
llama.cpp 本地部署完全指南
windows·llama·wsl·llamacpp
云上飞476369621 天前
Windows WSL2 + Docker 环境下NVIDIA PhysicsNeMo 安装指南
windows·docker·physicsai·physicsnemo
weixin_6681 天前
取消Windows 11 默认精简的鼠标右键文件夹菜单
windows·计算机外设
love530love1 天前
彻底清理 Windows 右键“打开方式“中的重复/失效程序项(PyCharm 多版本残留实战 + 自动化脚本)
运维·人工智能·windows·pycharm·jetbrains·toolbox
王维同学1 天前
进程模块枚举、映像身份与线程启动地址关联
c++·windows·安全
x²+(y-√³x²)²=12 天前
Linux打包文件到Windows,文件/文件类型丢失
linux·运维·windows
Rudon滨海渔村2 天前
windows10如何删除多余的输入法 - 仅保留English+拼音
windows·输入法