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

运行结果如下:

相关推荐
spencer_tseng14 小时前
Redis + Nacos.bat
java·windows·dos
会飞的小新15 小时前
Windows CMD 与 PowerShell 深度解析:底层原理、命令差异、自动化选型指南
运维·windows·自动化
ziguo112219 小时前
Windows API 文件操作超级指南——从入门到内核
c++·windows·visualstudio
七牛云行业应用21 小时前
Ollama 本地部署 DeepSeek 完全指南:macOS / Windows / Linux 三端安装 + GPU 配置 + API 调用
linux·windows·macos
Code Man21 小时前
Windows 下使用 Appium
android·windows·appium
WangWei_CM1 天前
Active Setup:按用户首次登录执行的组件初始化
windows
zandy10111 天前
体验家 XMPlus 问卷答题体验优化与完成率提升引擎:从交互设计到行为心理学的工程化实践
windows·microsoft·交互
独隅1 天前
DevEco Code 在 Windows/MacOS 双系统上的完整使用指南
ide·人工智能·windows·macos·华为·harmonyos
寒水馨1 天前
Windows下载、安装electron-v43.2.0(附安装包electron-v43.2.0-win32-x64.zip)
javascript·windows·typescript·electron·跨平台·桌面应用·chromium
x10n91 天前
常用 Windows 数据恢复工具横向汇总|误删文件、分区损坏自救软件清单
windows·数据恢复·数据恢复工具