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

运行结果如下:

相关推荐
UNbuff_02 小时前
Windows netstat 命令使用说明
windows
您的通讯录好友2 小时前
conda环境导出
linux·windows·conda
子兮曰6 小时前
🔥C盘告急!WSL磁盘暴增?三招秒清20GB+空间
前端·windows·docker
学历真的很重要8 小时前
Claude Code Windows 原生版安装指南
人工智能·windows·后端·语言模型·面试·go
李游Leo8 小时前
LaTeX TeX Live 安装与 CTAN 国内镜像配置(Windows / macOS / Linux 全流程)
linux·windows·macos
Jayin_chan9 小时前
windows下安装claude code+国产大模型glm4.5接入(无需科学上网)
windows·claude code·glm4.5
央链知播10 小时前
双轮驱动 六方协同--“可信资产IPO+数链金融RWA“链改2.0深圳共识发布
microsoft·金融
cpsvps_net11 小时前
Windows远程FX编解码优化
windows
Liquad Li11 小时前
Azure Data Factory (ADF) vs Azure Logic Apps: 对比分析
microsoft·azure
Liquad Li11 小时前
Azure Logic App 与 Azure Function 对比分析
microsoft·azure