• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How can I Iterate a map

 
Ashok Pradhan
Ranch Hand
Posts: 180
Eclipse IDE Firefox Browser Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
TreeMap is a sorted map.But, haw can I know that it is sorted map and I want to know the keys in the map are sorted or values are sorted ,then how can I iterate the TreeMap so that I know that it is sorted.
[ September 25, 2008: Message edited by: Ashok Pradhan ]
 
Seema Gaurav
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ashok,
Maps don't come with iterators. You will have to convert a Map to a Set in order to iterate through it. Map API has a method called entrySet() that returns a Set of Map.Entry elements. Entry is a static inner class of the Map interface that holds the key/value pair. You can use the getKey() and getValue() methods of the Map.Entry class to retrieve the key/value. You can look at the Map.Entry API for further details. Here's some sample code:


HTH,
Seema

[ September 25, 2008: Message edited by: Seema Gaurav ]

[ September 25, 2008: Message edited by: Seema Gaurav ]
[ September 25, 2008: Message edited by: Seema Gaurav ]
 
Leonid Shchervinsky
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
or for a quick test, you can just print the map:

class MapTest {

public static void main(String[] args) {
Map<Integer, String> map = new TreeMap<Integer, String>();
map.put(1, "Apple");
map.put(2, "Mango");
map.put(3, "Banana");
map.put(4, "Peach");

//Set<Map.Entry<Integer, String>> entry = map.entrySet();
//
//for (Map.Entry pairs : entry) {
// System.out.println("Key:" + pairs.getKey() + "Value:" + pairs.getValue());
//
//}

System.out.println(map);

}
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic