且构网

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

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

更新时间:2023-01-11 23:37:23

当您已经有工作要做时,为什么还要重新发明***.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());
    }

附注: -
你的代码在我看来很混乱.我建议,将代码放在一边,再考虑一下您的 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.