Friday, July 27, 2012

Value Sort using Generics


In Common, Java API sorts the data in map by keys if we need sort by value use following program.
Implementation:
package com.lenin;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class MapUtils {
      public static <K, V extends Comparable<? super V>> Map<K, V> valueSort(Map<K, V> map) {
            List<Map.Entry<K, V>> list = new ArrayList<Map.Entry<K, V>>(map.entrySet());
            Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
                  public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
                        return (o1.getValue()).compareTo(o2.getValue());
                  }
            });

            Map<K, V> result = new LinkedHashMap<K, V>();
            for (Map.Entry<K, V> entry : list) {
                  result.put(entry.getKey(), entry.getValue());
            }
            return result;
      }
}
Test:
package com.lenin;
import static com.lenin.MapUtils.valueSort;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public class MapUtilsTest {  
      public static void main(String[] args) {
            Map<String,String> map = new HashMap<String, String>();
            map.put("01", "one");
            map.put("02", "two");
            map.put("05", "one");
            map.put("10", "ten");
            map = valueSort(map);
            for(Entry<String,String> entry : map.entrySet()){
                  System.out.println(entry.getKey() + "-->" + entry.getValue());
            }
      }
}

No comments:

Post a Comment