如何减少列表多次遍历?优化按类型求和的Java代码
解决方案
核心逻辑是单次遍历对象列表,根据每个对象的type属性,直接将amount累加到Account类对应的属性中,彻底避免多次遍历的冗余操作。
示例实现(Python)
1. 定义Account类
先创建包含各类统计属性的Account类,根据实际业务需求定义对应的金额字段:
class Account: def __init__(self): self.income_total = 0 self.expense_total = 0 self.transfer_total = 0
2. 单次遍历完成多类型求和
遍历目标列表时,每处理一个对象就根据其type匹配到Account的对应属性,直接累加金额:
# 示例交易列表,替换为你的实际数据 transaction_list = [ {"type": "income", "amount": 1200}, {"type": "expense", "amount": 450}, {"type": "income", "amount": 800}, {"type": "transfer", "amount": 300}, {"type": "expense", "amount": 200} ] account = Account() for trans in transaction_list: trans_type = trans["type"] amount = trans["amount"] if trans_type == "income": account.income_total += amount elif trans_type == "expense": account.expense_total += amount elif trans_type == "transfer": account.transfer_total += amount # 可根据实际业务类型继续添加分支
优化方案(适配多类型场景)
如果业务中type类型较多,用if-elif分支会显得繁琐,可通过字典映射简化逻辑,后续新增类型只需维护映射字典即可:
class Account: def __init__(self): self.income_total = 0 self.expense_total = 0 self.transfer_total = 0 # 新增类型时只需在这里添加对应属性 # 建立type与Account属性的映射关系 type_attr_map = { "income": "income_total", "expense": "expense_total", "transfer": "transfer_total" } account = Account() for trans in transaction_list: trans_type = trans["type"] if trans_type in type_attr_map: # 动态获取并累加对应属性值 current_value = getattr(account, type_attr_map[trans_type]) setattr(account, type_attr_map[trans_type], current_value + trans["amount"])
内容的提问来源于stack exchange,提问作者iamro45
相关产品推荐
相关产品推荐

