且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从ArrayList Java中的HashMap键中检索所有值

更新时间:2023-01-11 23:20:15

当您已有工作要做时,为什么要重新发明***. Map.keySet()方法为您提供了Map中所有键的Set.

Why do you want to re-invent the wheel, when you already have something to do your work. Map.keySet() method gives you a Set of all the keys in the Map.

Map<String, Integer> map = new HashMap<String, Integer>();

for (String key: map.keySet()) {
    System.out.println("key : " + key);
    System.out.println("value : " + map.get(key));
}

此外,您的第一个for循环对我来说很奇怪:-

Also, your 1st for-loop looks odd to me: -

   for(int k = 0; k < list.size(); k++){
            map = (HashMap)list.get(k);
   }

您正在遍历列表,并将每个元素分配给相同的reference - map,这将覆盖所有先前的值.您将拥有的只是列表中的最后一个映射.

You are iterating over your list, and assigning each element to the same reference - map, which will overwrite all the previous values.. All you will be having is the last map in your list.

编辑:-

如果您想要地图的键和值,也可以使用entrySet.那对您来说更好:-

You can also use entrySet if you want both key and value for your map. That would be better bet for you: -

    Map<String, Integer> map = new HashMap<String, Integer>();

    for(Entry<String, Integer> entry: map.entrySet()) {
        System.out.println(entry.getKey());
        System.out.println(entry.getValue());
    }

PS :-
您的代码对我来说很混乱.我建议保留该代码,然后再考虑您的design.就目前而言,如代码所示,很难理解其意图.

P.S.: -
Your code looks jumbled to me. I would suggest, keep that code aside, and think about your design one more time. For now, as the code stands, it is very difficult to understand what its trying to do.