This week's book giveaways are in the Scala and Android forums.
We're giving away four copies each of Machine Learning Systems: Designs that scale and Xamarin in Action: Creating native cross-platform mobile apps and have the authors on-line!
See this thread and this one for details.
Win a copy of Machine Learning Systems: Designs that scale this week in the Scala forum
or Xamarin in Action: Creating native cross-platform mobile apps in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

How can I Iterate a map  RSS feed

 
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 ]
 
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 ]
 
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);

}
}
 
Seriously? That's what you're going with? I prefer this tiny ad:
Rocket Oven Kickstarter - from the trailboss
https://coderanch.com/t/695773/Rocket-Oven-Kickstarter-trailboss
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!