Dart中如何按键对比两个Map的值实现总座位数计算并简化代码
实现思路
直接遍历包含全量键的reserveMap的键集合即可,无需逐个硬编码键名做判断。你可以根据业务需求灵活调整相等/不等/键不存在场景的加减分值:
import 'package:collection/collection.dart'; void main() { compareValues(); } void compareValues() { int totalSeats = 0; // 可根据业务需求调整对应场景的加减分值,要加2/减2直接修改对应常量即可 const int matchScore = 1; const int mismatchScore = -1; const int bookingMissScore = -1; // bookingMap不存在该键时的分值 // Booking Map Map<String, int> bookingMap = { 'c1': 1, 'c2': 2, 'c3': 3, 'c4': 5, }; // 预留座位Map,包含全量键 Map<String, int> reserveMap = { 'c1': 1, 'c2': 2, 'c3': 3, 'c4': 4, 'c5': 6, }; // 遍历全量键逐个对比 for (final key in reserveMap.keys) { if (bookingMap.containsKey(key)) { final bookingVal = bookingMap[key]!; final reserveVal = reserveMap[key]!; totalSeats += bookingVal == reserveVal ? matchScore : mismatchScore; } else { // bookingMap不存在该键的自定义逻辑,不需要该规则可以注释掉这行 totalSeats += bookingMissScore; } } print(totalSeats); // 按上面的分值配置,示例输出为 1+1+1-1-1 = 1 }
如果你只需要对比
bookingMap中存在的键,忽略reserveMap有但bookingMap没有的键,把遍历对象换成bookingMap.keys即可,也不需要额外判断键是否存在。
内容的提问来源于stack exchange,提问作者Raj A
相关产品推荐
相关产品推荐

