简体   繁体   English

使用循环用数组填充键时,哈希映射键重新调整为空

[英]Hash map keys retuning null when using loop to populate key with array

    List<LineOfBusiness> lobArray = new ArrayList<>();
    Map<String,String> params = new LinkedHashMap<>();

    List<String> scoreValues = Stream.of(StandardizedScore.values())
            .filter(o -> !o.getExpectedAction().trim().isEmpty())
            .map(o -> String.format("%s,%s,%s", o.getClaimScore(), o.getNetworkScore(), o.getExpectedAction()))
            .collect(Collectors.toList());

    for (LineOfBusiness lob : LineOfBusiness.values()) {
        lobArray.add(lob);
    }

    for (int i = 0; i < lobArray.size(); i++){
        for (int j = 0; j < scoreValues.size(); j++) {
            System.out.println(params.put(lobArray.get(i).toString(), scoreValues.get(j)));
        }
    }

When I try and populate the HashMap with params.put(lobArray.get(i), scoreValues.get(j)) the keys return as null.当我尝试使用params.put(lobArray.get(i), scoreValues.get(j))填充HashMap ,键返回为 null。 The List is definitely populated as values print correctly when I print them in the loop using System.out.println(lobArray.get(i));当我使用System.out.println(lobArray.get(i));在循环中打印它们时,列表肯定会填充为正确打印的值System.out.println(lobArray.get(i)); . . I've tried to debug the code and it picks up the values from the list then too.我尝试调试代码,然后它也从列表中获取值。

Something is going wrong when I add the lobArray values as the key into the HashMap .当我将lobArray值作为键添加到HashMap If anyone could spot what is going wrong I'd be very grateful.如果有人能发现出了什么问题,我将不胜感激。

You are inserting the values correctly into your map.您正在将值正确插入到地图中。 It's just a matter of printing.这只是印刷的问题。 You should print the content of your map only after you have inserted your values into the map.只有将值插入地图,才应打印地图的内容。

Here's what I mean:这就是我的意思:

for (int i = 0; i < lobArray.size(); i++){
   for (int j = 0; j < scoreValues.size(); j++) {
       params.put(lobArray.get(i).toString(), scoreValues.get(j));
   }
}

System.out.println(params);

Or, if you want to iterate through the map entries, use entrySet , and do it like this:或者,如果您想遍历地图条目,请使用entrySet ,并按如下方式执行:

for (Map.Entry<String, String> param : params.entrySet()) {
   System.out.println(param);
}

Now, the reason you get null in your code.现在,您在代码中获得null的原因。 According to Map javadoc , the put method returns:根据Map javadocput方法返回:

the previous value associated with key, or null if there was no mapping for key.与 key 关联的先前值,如果没有 key 的映射,则为 null。 (A null return can also indicate that the map previously associated null with key, if the implementation supports null values.) (如果实现支持空值,则返回空值还可以指示映射先前将空值与键关联。)

You didn't have any value associated for your key before, that's why the null is printed.您之前没有任何与您的键相关联的值,这就是打印null的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM