猿问

如何重构地图转换操作

我写了一个关于将基本映射转换为另一个结构映射的逻辑,但是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 的评论:

我应该如何改进呢?谢谢



慕田峪9158850
浏览 106回答 1
1回答

暮色呼如

那么您不需要枚举rowentrySet 来检查键是否存在。你可以大大简化它,比如for (Map<String, Object> row : rows) {&nbsp; &nbsp; Object stock = row.get("stock");&nbsp; &nbsp; Object itemId = row.get("itemid");&nbsp; &nbsp; Object modelId = row.get("modelid");&nbsp; &nbsp; if (stock != null && itemId != null && modelId != null) {&nbsp; &nbsp; &nbsp; &nbsp; stockMap.put(Arrays.asList(modelId.toString(), itemId.toString()),&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; stock.toString());&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答