How can I iterate over a map of ?

前端 未结 2 1194
夕颜
夕颜 2020-11-29 13:58

I\'ve got a Map (actually I\'m using a more complex POJO but simplifying it for the sake of my question)

Person looks

2条回答
  •  日久生厌
    2020-11-29 14:33

    You can use:

    • Map.entrySet() (as mentioned by org.life.java) or,
    • Map.keySet() as in this example (based on your sampled code)

    Example:

    Map personMap = ..... //assuming it's not null
    Iterator strIter = personMap.keySet().iterator();
    synchronized (strIter) {
        while (strIter.hasNext()) {
            String key = strIter.next();
            Person person = personMap.get(key);
    
            String a = key;
            String b = person.getName();
            String c = person.getAge().toString();
            System.out.println(String.format("Key : %s Name : %s Age : %s", a, b, c));
    
        }
    }
    

提交回复
热议问题