skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Monday, October 15, 2012

Sort map key in ascending order

Posted by Raju Gupta at 10:00 AM – 0 comments
 
The code snippet can be plugged in to any java code, to sort the defined map in ascending order

public class NewClass1 {

 public static void main(String[] args) throws IOException {
  Map numMap = new HashMap();
  numMap.put("Key1", new ArrayList(Arrays.asList("K1V1", "K1V2", "K1V3")));
  numMap.put("Key2", new ArrayList(Arrays.asList("K2V1", "K2V2", "K2V3")));
  numMap.put("Key3", new ArrayList(Arrays.asList("K3V3", "K3V2", "K3V3")));
  numMap.put("Key4", new ArrayList(Arrays.asList("K4V1", "K4V2", "K4V3")));

  /* Sort map in ascending order */

  Map sortedMap = new TreeMap(numMap);
  Iterator itr = sortedMap.entrySet().iterator();
  System.out.println("In Ascending Order: ");

  /* Print map contents */

  while (itr.hasNext()) {

   Map.Entry keyValue = (Map.Entry) itr.next();

   System.out.println("Key: " + keyValue.getKey());

   List value = (List) keyValue.getValue();

   for (int i = 0; i < value.size(); i++) {

    if (value != null) {

     if (value.get(i) != null) {

      System.out.println("Value: " + value.get(i));

     }

    }

   }

  }
 }
}


Labels: Java Map Example

Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger