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

运行结果如下:

相关推荐
就改了2 小时前
Windows 环境 SkyWalking 完整实操教程
windows·微服务·skywalking
hai3152475433 小时前
九章编程法 · 猜数字游戏 (GW-BASIC 重构版) *
人工智能·microsoft·游戏引擎·游戏程序
郭wes代码4 小时前
Win10 拒绝访问、长期关机自动维护与声音图标灰色故障解决记录
windows·python·开源
2601_961875247 小时前
花生十三公考课程|网课|视频
数据库·windows·git·svn·eclipse·github
bkspiderx7 小时前
Windows DLL核心技术:深入理解__declspec(dllexport)与__declspec(dllimport)
windows·stm32·单片机·dllimport·dllexport·windows dll·__declspec
铁打的阿秀8 小时前
SQL server2025 Express安装及管理工具安装使用教程(Windows)
windows·sqlserver·express
疯狂成瘾者8 小时前
Java 常用工具包 java.util
java·开发语言·windows
无为之士8 小时前
Windows 批量打印 PDF 工具分享:支持文件夹、指定文件、当天文件、预览列表
windows·powershell
rhythm-ring9 小时前
TortoiseSVN 配置 Beyond Compare 注意事项
windows