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

运行结果如下:

相关推荐
线上放牧人4 小时前
Windows删除图标缓存
windows·python·pyqt
Koi慢热5 小时前
DayDayMap学术社区体验:卫星网络测绘专题用下来怎么样
网络·人工智能·windows·web安全·网络安全
web守墓人6 小时前
【goed/ui】自定义组件设计思想篇
linux·windows·ui·golang
Access开发易登软件8 小时前
Access 复杂业务计算,SQL 写在 VBA 还是存储过程?
microsoft·vba·access·access开发
2601_962364979 小时前
红外活体模组,Windows 设备安全身份入口解析
windows·安全·电脑
易点云徐源10 小时前
(已解决)Photoshop 2020 点击“选择主体”闪退:不用重装,1 个配置切回旧算法解决
windows·photoshop
云计算练习生10 小时前
什么是系统调用?为什么程序访问硬件必须经过它
linux·windows·操作系统·系统调用·操作系统原理
其实防守也摸鱼17 小时前
DeepSeek Harness 开源贡献手记:从入门到合入主线
服务器·数据库·windows·https·ssl
qqww15518 小时前
Win11更新后Edge卡顿掉帧?隐私窗口流畅解决办法
windows·edge·优化·卡顿
其实防守也摸鱼19 小时前
堆叠注入(Stacked Injection)详解
服务器·数据库·windows·https·ssl