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

运行结果如下:

相关推荐
海盗12341 小时前
微软技术周报 ——2026-08-03
后端·python·microsoft·c#·.netcore
趣味科技7 小时前
记录修复EAGET忆捷移动硬盘损坏
windows·数据分析·硬件工程
时空节拍AI数字人8 小时前
多模态交互数字人:语音+视觉+触控如何融合
人工智能·microsoft·ai·aigc·交互·语音识别
我命由我123459 小时前
Java 开发 - List subList 方法
java·windows·操作系统·list·intellij-idea·idea·intellij idea
吃辣我第一9 小时前
监听SHP目录自动注册SuperMap iServer地图服务(Windows版)
windows·iserver·shapefile
程序员老陆10 小时前
FFmpeg6 在 Windows 打开麦克风并录成 PCM:不走 Qt Multimedia,也不碰 WASAPI
windows·ffmpeg·音视频·pcm
chushiyunen10 小时前
神雕武功排名
windows
意图共鸣11 小时前
意图共鸣科技:人文驱动AI——从“能不能“到“好不好“
人工智能·microsoft
酩酊仙人11 小时前
Windows Server部署django
windows·django·sqlite
蓝斯4971 天前
从.到实现一个Windows上的虚拟hid键盘设备
windows·单片机·计算机外设