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

运行结果如下:

相关推荐
xiangyun614 小时前
C++ list 模拟实现(一):手撕双向链表,从节点到迭代器
数据库·c++·算法·链表·stl·list
imperialeast13 小时前
WinAXP 2.4.0.828正式版
windows
周小董15 小时前
[1369]Windows上安装PostgreSQL
数据库·windows·postgresql
doujiaozh15 小时前
Win7 复活记:用 3 个补丁让 13 年前的老电脑跑通 Kimi API
windows
bbq烤鸡1 天前
Win11 资源管理器“白条“修复报告
windows
10mAh1 天前
【Java】ArrayList 遍历删除为什么报错?三种写法与漏删复现
java·开发语言·windows
瑶山1 天前
Windows + WSL2 Ubuntu + VS Code配置C++开发环境
开发语言·c++·windows·vscode·wsl
在角落发呆1 天前
一键脚本配置备份方法:从 Shell 脚本到自动备份
网络·windows
水饺编程1 天前
第1章,[Win32 章节]:在 VS2019 里面安装 MSDN
c语言·c++·windows·visual studio
水饺编程1 天前
第1章,[Win32 章节]:编程环境与 MSDN
c语言·c++·windows·visual studio