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

运行结果如下:

相关推荐
超龄超能程序猿5 小时前
dnSpy 使用教程
windows·microsoft
Leinwin8 小时前
微软开源GitHub Copilot Chat,AI编程领域迎新突破
microsoft·github·copilot
路来了10 小时前
Python小工具之PDF合并
开发语言·windows·python
csdn_aspnet12 小时前
在 Windows 上安装和运行 Apache Kafka
windows·kafka
江山如画,佳人北望14 小时前
C#程序入门
开发语言·windows·c#
AustinCyy14 小时前
【环境配置】Neo4j Community Windows 安装教程
windows·neo4j
奇怪的杰哥15 小时前
Win11 加快软件开机自启动
windows
旷世奇才李先生15 小时前
Pillow 安装使用教程
深度学习·microsoft·pillow
cpsvps15 小时前
Windows内核并发优化
windows
qq_3938282220 小时前
电脑休眠设置
windows·电脑·软件需求