This week's book giveaway is in the Cloud/Virtualization forum.
We're giving away four copies of Learning OpenStack Networking: Build a solid foundation in virtual networking technologies for OpenStack-based clouds and have James Denton on-line!
See this thread for details.
Win a copy of Learning OpenStack Networking: Build a solid foundation in virtual networking technologies for OpenStack-based clouds this week in the Cloud/Virtualization forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

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

}
}
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!