aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes How can I Iterate a map Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "How can I Iterate a map" Watch "How can I Iterate a map" New topic
Author

How can I Iterate a map

Ashok Pradhan
Ranch Hand

Joined: Dec 17, 2007
Posts: 180

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

Joined: Apr 29, 2008
Posts: 47
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

Joined: Sep 07, 2006
Posts: 32
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);

}
}


<a href="http://www.shchervinsky.com/java/" target="_blank" rel="nofollow">http://www.shchervinsky.com/java/</a>
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How can I Iterate a map
 
Similar Threads
Collection doubt
Sorting Map
Treemap sorting O-notation ?
Problem with Treemaps
Sorted map -- can't get there from here?