How to iterate over a TreeMap?

Click Upvote picture Click Upvote · Aug 23, 2009 · Viewed 297.6k times · Source

Possible Duplicate:
How do I iterate over each Entry in a Map?

I want to iterate over a TreeMap, and for all keys which have a particular value, I want them to be added to a new TreeMap. How can I do this?

Answer

Zed picture Zed · Aug 23, 2009

Assuming type TreeMap<String,Integer> :

for(Map.Entry<String,Integer> entry : treeMap.entrySet()) {
  String key = entry.getKey();
  Integer value = entry.getValue();

  System.out.println(key + " => " + value);
}

(key and Value types can be any class of course)