You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否通过索引获取LinkedHashMap的值?如何比较两个映射的对应属性?

关于LinkedHashMap的索引访问与值比较问题

能不能通过索引获取LinkedHashMap的值?

LinkedHashMap本身没有提供直接通过索引获取元素的方法——它本质是键值对映射结构,核心设计是通过键(key)访问值(value),而非索引。但因为LinkedHashMap维护了元素的插入顺序,我们可以把它的键值对(entry)转换成列表,再通过索引访问:

// 将LinkedHashMap的entry集合转为ArrayList,保留插入顺序
List<Map.Entry<String, ChargeType>> entryList = new ArrayList<>(chargeTypeCol.entrySet());
// 通过索引获取对应的值
ChargeType target = entryList.get(0).getValue();

如何比较两个LinkedHashMap的value属性?

你想比较两个LinkedHashMap中value的chargeTypeName、amount、quantity是否相等,有两种实用实现方式:

方式一:转列表后按索引遍历(匹配你提供的列表遍历写法)

先把两个LinkedHashMap的entry转成列表,再用双重索引循环匹配:

// 转换两个LinkedHashMap为entry列表
List<Map.Entry<String, ChargeType>> list1 = new ArrayList<>(chargeTypeCol1.entrySet());
List<Map.Entry<String, ChargeType>> list2 = new ArrayList<>(chargeTypeCol2.entrySet());

for (int i = 0; i < list1.size(); i++) {
    ChargeType ct1 = list1.get(i).getValue();
    for (int j = 0; j < list2.size(); j++) {
        ChargeType ct2 = list2.get(j).getValue();
        // 先匹配chargeTypeName(忽略大小写)
        if (ct1.getChargeTypeName().equalsIgnoreCase(ct2.getChargeTypeName())) {
            // 再比较amount和quantity
            if (ct1.getAmount().equals(ct2.getAmount()) && ct1.getQuantity().equals(ct2.getQuantity())) {
                // 执行你的业务逻辑
            }
        }
    }
}

方式二:利用Map的键直接匹配(更高效)

因为你的LinkedHashMap的键就是chargeTypeName,直接通过键查找匹配的value,无需双重循环,效率更高:

for (Map.Entry<String, ChargeType> entry : chargeTypeCol1.entrySet()) {
    ChargeType ct1 = entry.getValue();
    String typeName = ct1.getChargeTypeName();
    // 若Map键区分大小写,可转统一大小写后查找;键严格一致则直接用chargeTypeCol2.get(typeName)
    ChargeType ct2 = chargeTypeCol2.get(typeName.toLowerCase());
    
    if (ct2 != null) {
        // 比较amount和quantity
        if (ct1.getAmount().equals(ct2.getAmount()) && ct1.getQuantity().equals(ct2.getQuantity())) {
            // 执行你的业务逻辑
        }
    }
}

注意:如果amount或quantity是BigDecimal、Integer这类包装类,要用equals比较而非==;若是浮点型(double/float),建议用精度比较避免误差。

内容的提问来源于stack exchange,提问作者poojay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 17:40:36