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

运行结果如下:

相关推荐
2501_946244781 小时前
Flutter & OpenHarmony OA系统弹窗对话框组件开发指南
javascript·flutter·microsoft
天才程序YUAN4 小时前
Windows自动修改系统环境变量(PATH)中所有 D 盘路径的脚本
运维·windows
幺零九零零4 小时前
Windows + Docker + k6 + InfluxDB + Grafana
windows·docker·grafana
s45 小时前
Python安装在C盘后如何移到D盘
c语言·windows·python
`林中水滴`6 小时前
Linux Shell 命令:nohup、&、>、bg、fg、jobs 总结
linux·服务器·microsoft
芒鸽6 小时前
windows上使用Lycium 交叉编译移植鸿蒙三方库指南
windows·华为·harmonyos
3824278276 小时前
JS逆向:DOM交互与window.onload详解
microsoft
shizhenshide6 小时前
物联网(IoT)设备如何应对验证码?探讨无头浏览器与协议级解决方案
java·struts·microsoft·验证码·ezcaptcha
清水白石0086 小时前
《Python 中 deque vs list:性能差异全解析与高效数据结构实战指南》
数据结构·python·list
FL16238631296 小时前
flash_attn windows whl下载安装教程
windows·stm32·单片机