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

运行结果如下:

相关推荐
醉城夜风~13 小时前
(超详细)C++ STL list容器详解:从使用方法到双向链表底层原理全面解析
c++·windows
凤山老林14 小时前
在 Apple 芯片的 Mac 上通过 VMware Fusion 使用 Windows 11
windows·macos·vmware·虚拟机
不弃君14 小时前
在 Windows 上用 MinGW 搭建 lwIP 调试环境:方法与踩坑实录
windows·网络协议·tcp/ip·嵌入式·mingw·lwip
ITHAOGE1515 小时前
下载 | Win11 24H2 正式版更新!(系统ISO映像、多合一版本、26100.8973、Windows 11)
windows·科技·微软·电脑
lzhdim19 小时前
C# 通过 Windows API 实现进程内存读写操作
开发语言·windows·c#
CIAS21 小时前
Windows powershell下实现空间释放
windows
AxureMost1 天前
NeeView图像查看
windows
赵广陆1 天前
Model I/O进阶
windows
问商十三载1 天前
RAG 检索效果差怎么排查?2026 五层诊断法完整指南
开发语言·人工智能·windows·python·算法
Zguigo1 天前
第25-26讲:计算机操作系统存储管理——分页机制、页表与快表(TLB)
linux·windows·笔记