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

运行结果如下:

相关推荐
爱潜水的小L22 分钟前
自学嵌入式day36,mplayer+fifo+exec
网络·windows
酩酊仙人1 小时前
告别IIS依赖!ASP.NET Core如何通过Windows Service实现服务托管
windows·后端·asp.net
YHPsophie1 小时前
HT4125低压CMOS缓冲门器件特性及应用深度解析
microsoft
CS Beginner10 小时前
【C语言】windows下编译mingw版本的glew库
c语言·开发语言·windows
别来无恙blwy16 小时前
SQL Server高可用自动故障转移失败(短时间内多次转移失败,只需一步可处理)
数据库·windows·sqlserver·负载均衡·可用性测试
CodeLinghu20 小时前
路由:Agent能够根据条件动态决定工作流的下一步
人工智能·microsoft·ai·llm
石像鬼₧魂石20 小时前
SET的钓鱼网站钓鱼模块
windows·学习·ubuntu
喵了几个咪20 小时前
开箱即用的 GoWind Admin|风行,企业级前后端一体中后台框架:Makefile 在后端开发中的应用与 Windows 环境配置
windows
love530love1 天前
在 PyCharm 中配置 x64 Native Tools Command Prompt for VS 2022 作为默认终端
ide·人工智能·windows·python·pycharm·prompt·comfyui
gf13211111 天前
python_制作视频开头_根据短句字长占总字幕的长度比例拆分
windows·python·音视频