How to iterate over a TreeMap?

JavaCollectionsTreemap

Java Problem Overview


> 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?

Java Solutions


Solution 1 - Java

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)

Solution 2 - Java

    //create TreeMap instance
    TreeMap treeMap = new TreeMap();
 
    //add key value pairs to TreeMap
    treeMap.put("1","One");
    treeMap.put("2","Two");
    treeMap.put("3","Three");
 
    /*
      get Collection of values contained in TreeMap using
      Collection values()        
    */
    Collection c = treeMap.values();
 
    //obtain an Iterator for Collection
    Iterator itr = c.iterator();
 
    //iterate through TreeMap values iterator
    while(itr.hasNext())
      System.out.println(itr.next());

or:

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

or:

   // Use iterator to display the keys and associated values
   System.out.println("Map Values Before: ");
   Set keys = map.keySet();
   for (Iterator i = keys.iterator(); i.hasNext();) {
     Integer key = (Integer) i.next();
     String value = (String) map.get(key);
     System.out.println(key + " = " + value);
   }

Solution 3 - Java

Just to point out the generic way to iterate over any map:

 private <K, V> void iterateOverMap(Map<K, V> map) {
	for (Map.Entry<K, V> entry : map.entrySet()) {
	    System.out.println("key ->" + entry.getKey() + ", value->" + entry.getValue());
	}
    }

Solution 4 - Java

Using Google Collections, assuming K is your key type:

Maps.filterKeys(treeMap, new Predicate<K>() {
  @Override
  public boolean apply(K key) {
    return false; //return true here if you need the entry to be in your new map
  }});

You can use filterEntries instead if you need the value as well.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAliView Question on Stackoverflow
Solution 1 - JavaZedView Answer on Stackoverflow
Solution 2 - Javakarim79View Answer on Stackoverflow
Solution 3 - JavaPriyank DoshiView Answer on Stackoverflow
Solution 4 - JavaJornView Answer on Stackoverflow