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

运行结果如下:

相关推荐
怎么没有名字注册了啊9 小时前
Qt开发:MessageBox怎么调出标题栏那个问号按钮?
windows
李子红了时10 小时前
EncFS MP中文版汉化下载(免费文件加密工具)
windows·安全
辻弋20110 小时前
五年前的旅行视频糊成马赛克?Video2X用Real-ESRGAN逐帧重建细节,但只支持Windows、集显用户建议直接放弃
服务器·数据库·windows·游戏引擎·电脑
会飞的土拨鼠呀11 小时前
Windows 系统关闭虚拟内存文件pagefile.sys
windows
传奇开心果编程13 小时前
【Compose Multiplatform 跨端开发学与练】第7课 平台适配与互操作
android·windows·学习·ui·ios·kotlin·composer
工作10年+,存储芯片行业13 小时前
Linux NVMe 中断排查与性能优化:CPU 亲和性
linux·运维·服务器·windows·性能优化·ssd·pcie
lpfasd12314 小时前
WinSW在Win7上失败真相-实测与修复
windows·nginx
万山寒15 小时前
windows使用WinSW注册服务
windows
白搞电子17 小时前
ESP32-S31 项目如何制作 Windows 一键烧录包:完整镜像、esptool 与数据边界
windows·stm32·单片机
apple_6926588518 小时前
Github开源免费 红果短剧 Windows 电脑桌面版:民间开发者做的第三方播放器,不用装模拟器了
windows