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

运行结果如下:

相关推荐
XUHUOJUN7 小时前
Windows 2025架构深度分析之Stretch Cluster 延迟工程现实
windows·microsoft·架构·azure local
love530love8 小时前
将 ChatCut MCP 插件从 Codex 桌面应用移植到 WorkBuddy —— 完整适配实录
ide·人工智能·windows·视频剪辑·ai agent
works cart8 小时前
windows常用命令
windows
浩浩测试一下10 小时前
windows 加壳工具代码实现02 - 加壳界面实现MFC
windows·mfc·免杀·加壳器·pe应用
崖边看雾13 小时前
记录Python学习——第一章环境安装下载(Windows)
windows·python·学习·pycharm
sukalot15 小时前
windows网络适配器驱动开发-NetAdapterCx 接收端缩放(中)
windows·驱动开发
我是Superman丶16 小时前
Windows系统FFmpeg官方下载+完整安装配置保姆级教程(2026最新版)
windows·ffmpeg
zandy101117 小时前
嵌入式BI PaaS:重构企业应用的数据智能生态
microsoft·重构·paas
weixin_4334176717 小时前
TortoiseGit推送到远端,如何配置
windows·git
2601_962364971 天前
Windows Hello VS 传统密码:身份认证安全层级全面对比分析
windows·安全·电脑