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

运行结果如下:

相关推荐
2601_962364974 小时前
重装系统后,Windows Hello 为什么要重新录入人脸?
windows·安全·电脑
水饺编程4 小时前
第5章,[Win32 章节] :在平面直角坐标系中描点
c语言·c++·windows·visual studio
蓝速科技5 小时前
企业展厅数字人导览效果提升与选型实战指南丨蓝速科技
大数据·运维·数据库·人工智能·科技·microsoft
三玖诶6 小时前
DeepSeek Launcher:内置 Node.js,为什么首次启动仍需要网络?
windows·开源·deepseek
陈天伟教授6 小时前
具身数据采集黑话(4)
人工智能·windows·具身智能
无巧不成书02186 小时前
Apache Tomcat 9 下载全指南(Windows,Linux,macOS):版本选型、国内镜像、SHA-512 与 PGP 完整性校验
windows·tomcat·apache
3Q工具箱 - BraggTroy7 小时前
Python + PyInstaller 实战:从零打造 10 个 Windows 桌面小工具(附全部踩坑记录与核心代码)
开发语言·windows·python
linnux领域7 小时前
eNSP 交换机与电脑不在一个网段?用一台 Windows 双网卡做路由,把实验环境彻底打通
windows·华为·电脑·ensp·静态路由·网络实验·ensp模拟器
挂科边缘7 小时前
Android Studio 保姆级安装教程,Windows 电脑上安装 Android Studio
android·windows·android studio
TechExplorer3658 小时前
Win11 必要禁用的服务以释放进程内存
windows