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

运行结果如下:

相关推荐
vfvfb3 小时前
bat批量去掉本文件夹中的文件扩展名
服务器·windows·批处理·删除扩展名·bat技巧
我命由我123459 小时前
VSCode - VSCode 放大与缩小代码
前端·ide·windows·vscode·前端框架·编辑器·软件工具
PT_silver10 小时前
tryhackme——Abusing Windows Internals(进程注入)
windows·microsoft
爱炸薯条的小朋友10 小时前
C#由于获取WPF窗口名称造成的异常报错问题
windows·c#·wpf
Lw老王要学习11 小时前
VScode 使用 git 提交数据到指定库的完整指南
windows·git·vscode
Leinwin12 小时前
微软推出SQL Server 2025技术预览版,深化人工智能应用集成
人工智能·microsoft
CoderJia程序员甲13 小时前
MCP 技术完全指南:微软开源项目助力 AI 开发标准化学习
microsoft·ai·开源·ai教程·mcp
泽020214 小时前
C++之STL--list
开发语言·c++·list
宝桥南山15 小时前
Microsoft Copilot Studio - 尝试一下Agent
microsoft·ai·微软·copilot·rpa·low-code
CodeOfCC17 小时前
c语言 封装跨平台线程头文件
linux·c语言·windows