java - 如何重构 map 转换操作

标签 java

我写了一个关于将基本映射转换为另一个结构映射的逻辑,但是SonarLint评论它需要重构,这里是代码:

public static Map<List<String>, String> toStockMap(List<Map<String, Object>> rows) {
    Map<List<String>, String> stockMap = new HashMap<>();
    if (CollectionUtils.isEmpty(rows)) {
        return stockMap;
    }
    for (Map<String, Object> row : rows) {
        String stock = null;
        String itemId = null;
        String modelId = null;
        for (Map.Entry<String, Object> cell : row.entrySet()) {
            if (cell.getKey().equals("stock")) {
                stock = cell.getValue().toString();
            }
            if (cell.getKey().equals("itemid")) {
                itemId = cell.getValue().toString();
            }
            if (cell.getKey().equals("modelid")) {
                modelId = cell.getValue().toString();
            }
        }
        if (stock != null && itemId != null && modelId != null) {
            stockMap.put(Arrays.asList(modelId, itemId), stock);
        }
    }
    return stockMap;
}

以及下面的sonarlint评论: sonarlint

我应该如何改进呢?谢谢

最佳答案

您不需要枚举rowentrySet 来检查键是否存在。你可以大大简化它,比如

for (Map<String, Object> row : rows) {
    Object stock = row.get("stock");
    Object itemId = row.get("itemid");
    Object modelId = row.get("modelid");
    if (stock != null && itemId != null && modelId != null) {
        stockMap.put(Arrays.asList(modelId.toString(), itemId.toString()), 
                stock.toString());
    }
}

关于java - 如何重构 map 转换操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57863489/

相关文章:

java - SecureRandom 的 SHA1PRNG 算法是否使用/dev/random 作为熵?

Java:从父类引用子类中的字段

java - 无法访问类型 foo 的封闭实例。为什么?

java - reCaptcha 在用 Google 验证时总是返回 false

java - Gui 的按钮布局问题

java - 使用 HTMLUnit 连接到 URL 时出现错误消息

java - 如何将 JPopup 移动到 Glasspane

java - JAVA 中将文件或 byte[] 转换为 BLOB

Java:线程将参数传递给另一个线程

java - 牛顿拉夫逊无解