skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Monday, October 15, 2012

Sort map in descending order

Posted by Raju Gupta at 8:00 AM – 0 comments
 
The code snippet provides a solution to sort the map in descending order.

public class NewClass1 {

 public static void main(String[] args) throws IOException {
  System.out.println("In Descending Order: ");

  /* Compares the keys and sorts the map in descending order */

  TreeMap map = new TreeMap(new Mycompare());
  map.put("Key1", new ArrayList(Arrays.asList("K1V1", "K1V2", "K1V3")));
  map.put("Key2", new ArrayList(Arrays.asList("K2V1", "K2V2", "K2V3")));
  map.put("Key3", new ArrayList(Arrays.asList("K3V3", "K3V2", "K3V3")));
  map.put("Key4", new ArrayList(Arrays.asList("K4V1", "K4V2", "K4V3")));
  Iterator itr1 = map.entrySet().iterator();

  /* To print the contents of the map */

  while (itr1.hasNext()) {

   Map.Entry keyValue = (Map.Entry) itr1.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));
     }
    }
   }
  }
 }
}

class Mycompare implements Comparator {

 public int compare(Object o1, Object o2)
 {
  String i1 = (String) o1;
  String i2 = (String) o2;
  return -i1.compareTo(i2);
 }

}


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