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

运行结果如下:

相关推荐
代码小书生5 小时前
Windows X-Lite Win11 26H1 v3 游戏优化系统!集Win11、Win10、Win7三代优点,兼顾游戏办公生产算力,系统精简纯净!
windows·win10·电脑系统·windows10·26h1·windows x-lite·操作系统操作系统
贵沫末7 小时前
python——打包自己的库并安装
开发语言·windows·python
小眼哥8 小时前
SpringBoot整合Vue代码生成exe运行程序以及windows安装包
vue.js·windows·spring boot
xiaoshuaishuai89 小时前
C# GPU算力与管理
开发语言·windows·c#
专注VB编程开发20年9 小时前
Webbrowser控件加载IE不同版本内核-注册表设置
microsoft·ie·webbrowser
꯭爿꯭巎꯭12 小时前
千鹿PR助手邀请码
windows
张赐荣13 小时前
跨平台无障碍版随机数生成器
windows
胖少年13 小时前
从零开始:在 Windows 上用 llama.cpp 跑本地大模型
windows·llama
小狄同学呀14 小时前
同样的global,不同的audioLibPath——记一次诡异的内存错位
c++·windows