java中根据某一属性比较两个list集合是否相同

 // 创建两个示例列表
    List<Map<String, Object>> list1 = new ArrayList<>();
    List<Map<String, Object>> list2 = new ArrayList<>();

    // 添加示例数据到列表中
    Map<String, Object> map1 = new HashMap<>();
    map1.put("id", 1);
    map1.put("name", "John");
    map1.put("age", 25);
    list1.add(map1);

    Map<String, Object> map2 = new HashMap<>();
    map2.put("id", 2);
    map2.put("name", "Alice");
    map2.put("age", 30);
    list1.add(map2);

    Map<String, Object> map3 = new HashMap<>();
    map3.put("id", 1);
    map3.put("name", "John");
    map3.put("age", 25);
    list2.add(map3);

    Map<String, Object> map4 = new HashMap<>();
    map4.put("id", 3);
    map4.put("name", "Alice");
    map4.put("age", 35);
    list2.add(map4);

    // 比较两个列表的name属性是否相同
    boolean isSameName = list1.stream()
            .map(map -> map.get("name"))
            .allMatch(name -> list2.stream()
                    .map(map -> map.get("name"))
                    .anyMatch(name::equals));

    System.out.println("isSameName: " + isSameName);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
可以使用Java的Stream API来实现这个功能。具体实现方法如下: 1. 使用Stream的map方法将集合对象转化成属性值的集合; 2. 使用Stream的distinct方法去重; 3. 使用Stream的count方法统计去重后的元素个数,如果为1则说明两个集合对象某个属性值全部相等,否则不相等。 示例代码如下: ```java public static boolean isPropertyEqual(List<?> list1, List<?> list2, String propertyName) { // 将集合对象转化成属性值的集合 List<Object> propertyList1 = list1.stream().map(obj -> { try { Field field = obj.getClass().getDeclaredField(propertyName); field.setAccessible(true); return field.get(obj); } catch (NoSuchFieldException | IllegalAccessException e) { e.printStackTrace(); return null; } }).collect(Collectors.toList()); // 将集合对象转化成属性值的集合 List<Object> propertyList2 = list2.stream().map(obj -> { try { Field field = obj.getClass().getDeclaredField(propertyName); field.setAccessible(true); return field.get(obj); } catch (NoSuchFieldException | IllegalAccessException e) { e.printStackTrace(); return null; } }).collect(Collectors.toList()); // 去重 propertyList1 = propertyList1.stream().distinct().collect(Collectors.toList()); propertyList2 = propertyList2.stream().distinct().collect(Collectors.toList()); // 统计去重后的元素个数,如果为1则说明两个集合对象某个属性值全部相等,否则不相等 return propertyList1.size() == 1 && propertyList2.size() == 1 && propertyList1.get(0).equals(propertyList2.get(0)); } ``` 其list1和list2分别表示两个集合,propertyName表示要比较属性名。返回值为一个布尔值,表示两个集合对象某个属性是否全部相等。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿杰同学

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值