Geeks With Blogs
Thomas Pepe

Java has a handy class that retains the order in which map (dictionary in .NET) values can be iterated in the same order they were added called LinkedHashMap.

Ways to iterate (*Coding from memory without compiler = chance for syntax errors: high):

LinkedHashMap<String,String> states = new LinkedHashMap<String,String>();
states.put("AL", "Alabama");
states.put("AK", "Alaska");
for(Map.Entry<String,String> state : states.entrySet()){
  System.out.print("state: " + state.getValue());
  System.out.println(" abbreviation: " + state.getKey());
}

OR

... while(states.entrySet().iterator().hasNext()){
  System.out.print("state: " + states.entrySet().getValue());
  System.out.println(" abbreviation: " + states.entrySet().getKey());
}

I discovered the LinkedHashMap thanks to this blog entry (thanks, Nick!): http://ironboundsoftware.com/blog/2006/10/14/an-ordered-hashmap-in-java/

Other references:
http://r4r.co.in/java/advancejava/collections/basic/example/collections_basic_examples.php?qid=845
http://stackoverflow.com/questions/4110045/get-next-item-in-linkedhashmap

Posted on Sunday, July 31, 2011 8:56 AM Java | Back to top


Comments on this post: Ordered Dictionary in Java

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © tom | Powered by: GeeksWithBlogs.net