java判断两个List是否存在相同元素

java判断两个List是否存在相同元素

package cn.包名.路径.demo;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 孙永潮
 * @date 2024/01/03
 */
public class ListDemo {
    public static void main(String[] args) {

        List<Integer> list1 = new ArrayList<>();
        list1.add(1);
        list1.add(2);
        list1.add(3);

        if (CollUtil.isEmpty(list1)){
            System.out.println("list1 为空集合");
        }

        List<Integer> list2 = new ArrayList<>();
        list2.add(4);
        list2.add(5);
        list2.add(6);

        if (CollUtil.isEmpty(list2)){
            System.out.println("list2 为空集合");
        }

        //anyMatch()方法 来检查 任何一个list1中的元素 在list2中是否存在。
        boolean hasCommonElements = list1.stream()
                .anyMatch(list2::contains);
                
        if (hasCommonElements){
            System.out.println("存在相同元素");

            //把相同元素找出来
            list1.addAll(list2);
            String repetition = list1.stream()
                    .collect(Collectors.groupingBy(c -> c))
                    .entrySet()

                    .stream()
                    .filter(e -> e.getValue().size() > 1)
                    .map(Map.Entry::getKey)
                    .collect(Collectors.toList())

                    .stream()
                    .map(Convert::toStr)
                    .collect(Collectors.joining("、"));

//如果是字符串,可以这样写
//        String duplicate = codes.stream()
//                .collect(Collectors.groupingBy(e -> e, Collectors.counting()))
//                .entrySet()
//                .stream()
//                .filter(e -> e.getValue() > 1L)
//                .map(Map.Entry::getKey)
//                .collect(Collectors.joining("、"));

// 如果是List里的某个元素查重,可以这样写
//        String netPointCode = list.stream()
//                .collect(Collectors.groupingBy(CylDTO::getCode, Collectors.counting()))
//                .entrySet()
//                .stream()
//                .filter(e -> e.getValue() > 1L)
//                .map(Map.Entry::getKey)
//                .collect(Collectors.joining("、"));

            if (StrUtil.isNotBlank(repetition)) {
                System.out.println("相同元素为:" + repetition);
            }

        }else {
            System.out.println("不存在相同元素");
        }
    }
}
  • 17
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值