list与list之间当某个属性值相等时,设置其他属性

本文介绍如何利用Java Stream API简化复杂的循环逻辑,通过示例对比了传统双重for循环与Stream流处理方式的区别,展示了Stream在集合操作上的高效性和简洁性。
if (firstUserWithdrawalNumList.size()>0&&firstUserWithdrawalNumList.get(0)!=null){
					List<UserHomeData> list = userHomeList.stream()
							.map(userHomeData -> firstUserWithdrawalNumList.stream()
									.filter(firstData -> userHomeData.getReportDay().equals(firstData.getCheckday()))
									.findFirst()
									.map(firstData -> {
										userHomeData.setWithdrawNumTotal(firstData.getNumTotal());
										userHomeData.setWithdrawMoneyTotal(firstData.getMoneyTotal());
										return userHomeData;
									}).orElse(userHomeData))
							.collect(Collectors.toList());

					userHomeList=list;
				}

使用stream代替双重for循环

     if (idslists.size()>0){
        for (int i=0;i<idslists.size();i++){
          for (int j=0;j<fisrtList.size();j++){
           if (fisrtList.get(j).getId().equals(idslists.get(i).getCategoryId())){
               list.add(fisrtList.get(j));
                      }
                 }
             }
        }

        if (idslists.size()>0){
         list=fisrtList.stream().filter((treeVo) ->
            idslists.stream().anyMatch(item-> treeVo.getId().equals(item.getCategoryId()))
         ).collect(Collectors.toList());
        }

在 Python 中,如果你有一个 **对象列表(list of objects)**,并想判断其中是否有某个对象的 **指定属性存在且等于某个**,可以使用多种方法实现。 --- ### ✅ 解决方案:使用 `hasattr()` `getattr()` 判断属性是否存在并比较 ```python class Person: def __init__(self, name, age): self.name = name self.age = age # 示例对象列表 people = [ Person("Alice", 25), Person("Bob", 30), Person("Charlie", 35) ] # 要检查:是否存在一个对象,其属性 'name' 存在且等于 "Bob" target_name = "Bob" # 方法1:使用 any() + hasattr() + getattr() exists = any(hasattr(p, 'name') and getattr(p, 'name') == target_name for p in people) print(exists) # 输出: True # 方法2:只使用 getattr 并提供默认(更简洁) value_to_match = "Alice" exists = any(getattr(p, 'name', None) == value_to_match for p in people) print(exists) # True ``` --- ### 🔍 解释: - `hasattr(obj, 'attr')`:检查对象是否具有该属性。 - `getattr(obj, 'attr', default)`:获取属性值,如果不存在返回 `default`(推荐用于避免异常)。 - `any(...)`:只要有一个匹配就返回 `True`,适合“是否存在”这类判断。 > ⚠️ 注意:直接访问 `obj.attr` 在属性不存在会抛出 `AttributeError`,所以推荐用 `getattr` 配合默认。 --- ### ✅ 扩展:找出所有满足条件的对象 ```python # 找出所有 name == "Alice" 的对象 matches = [p for p in people if getattr(p, 'name', None) == "Alice"] print(len(matches)) # 1 ``` --- ### ✅ 检查属性是否存在(不比较) ```python # 判断是否存在至少一个对象拥有 'age' 属性 has_age = any(hasattr(p, 'age') for p in people) print(has_age) # True ``` --- ### ✅ 对字典-like 对象也适用?可以统一处理! 如果列表中是 `dict` 或混合类型,也可以用类似逻辑: ```python data = [ {"name": "Alice", "age": 25}, Person("Bob", 30), {"age": 35} # 缺少 name ] # 安全判断:是否存在某个条目,其 'name' == "Bob" exists = any( getattr(item, 'name', None) == "Bob" if hasattr(item, '__class__') else item.get('name') if isinstance(item, dict) else False for item in data ) print(exists) # True ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值