Search code examples
javacollectionstreemap

How to iterate over a TreeMap?


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?


Solution

  • 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)