Tuesday, 9 February 2016

Sort java.util.Map by Value or Key

How to sort java.util.Map based on Key and Value:

In many occasions we need to sort a key value paired Map. We can easily do this by the two methods explained below:
1. Sorting a Map(Hashmap) based on key using java.util.TreeMap
2. Sorting a Map(HashMap) based on value using Comparator


Sort a Map By Key:
Here is a sample code which shows how to sort a Hashmap on key using TreeMap.

File: SortMap.java

package net.codermag.example;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class SortMap {
 public static void main(String[] args) {

  Map<Object, Object> objectMap = new HashMap<Object, Object>();
  objectMap.put("for", "java");
  objectMap.put("apple", "orange");
  objectMap.put("codermagnet", "is");
  objectMap.put("sort", "hashmap");

  Map<Object, Object> sortedMap = new TreeMap<Object, Object>(objectMap);
  System.out.println(sortedMap);

 }
}
Output:

{apple=orange, codermagnet=is, for=java, sort=hashmap}


Sort a Map By Value:
We can sort a HashMap using the value fields of the map. For this we need to use Comparator class.

File: SortMap.java

package net.codermag.example;

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class SortMap {
 public static void main(String[] args) {

  Map<Object, Object> objectMap = new HashMap<Object, Object>();
  objectMap.put("for", "java");
  objectMap.put("apple", "orange");
  objectMap.put("codermagnet", "is");
  objectMap.put("sort", "hashmap");

  System.out.println(sortByValue(objectMap));

 }

 @SuppressWarnings("unchecked")
 public static Map sortByValue(Map unsortMap) {
  List list = new LinkedList(unsortMap.entrySet());

  Collections.sort(list, new Comparator() {
   public int compare(Object object1, Object object2) {
    return ((Comparable) ((Map.Entry) (object1)).getValue())
      .compareTo(((Map.Entry) (object2)).getValue());
   }
  });

  Map sortedMap = new LinkedHashMap();
  for (Iterator it = list.iterator(); it.hasNext();) {
   Map.Entry entry = (Map.Entry) it.next();
   sortedMap.put(entry.getKey(), entry.getValue());
  }
  return sortedMap;
 }
}


Output:

{sort=hashmap, codermagnet=is, for=java, apple=orange}

Pitfall:

A thing you must remember while sorting a Map or any collection is that the data type of element being sorted must be of the same type. This means when sorting by key then all the datatype of the keys must be of one type. Similarly all values should be of same type when being sorted.

For Example:
When sorting a HashMap by Key:

The 1st map gets sorted because all the keys are of same datatype. In this case they are all Strings.
The 2nd map doesnot work as in this casewe are sorting by Keys of the map and they are not of the same type.


When sorting a HashMap by Value:

The 1st map gets sorted because all the values are of same datatype. In this case they are all Strings.
The 2nd map could not be sorted when sorting based on value because the values are not of the same type. There is a boolean and a NULL type which raises an exception.



No comments:

Post a Comment

Coder Magnet
CoderMagnet is full of resources from our daily development activities. It has solutions for common problematic scenarios in technologies like Java 8, AEM, JCR and also occasionally gives you tips on Blogger as well.