import java.util.ArrayList;
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;
import java.util.Map.Entry;
public class Program3 {
Map<String,String> map = new HashMap<String,String>();
//SortedMap<String,String> map = new TreeMap(new MyCompatator());
public static void main(String args[]){
Program3 p = new Program3();
p.map.put("g","f");
p.map.put("z","u");
p.map.put("e","z");
p.map.put("c","e");
p.map.put("b","b");
//p.map=customKeySort(p.map); // default sorting
//p.map=customValueSort(p.map); // custom sorting by value
p.map= customKeySort(p.map); // custom sorting by key
Iterator<String> it = p.map.keySet().iterator();
while(it.hasNext()){
String key = it.next();
System.out.println(key+" >> "+p.map.get(key));
}
}
public static <key extends Comparable,Val extends Comparable> Map<key,Val> DefaultKeySort(Map<key,Val> map){
List<key> keys = new ArrayList<key>(map.keySet());
Collections.sort(keys);
Map sortedMap = new LinkedHashMap();
for(Object key: keys){
sortedMap.put(key, map.get(key));
}
return sortedMap;
}
public static <key extends Comparable,Val extends Comparable> Map<key,Val> customValueSort(Map<key,Val> map){
List<Entry<key, Val>> Val = new ArrayList<Entry<key, Val>>(map.entrySet());
Collections.sort(Val,new Comparator<Entry<key, Val>>() {
@Override
public int compare(Entry<key, Val> o1, Entry<key, Val> o2) {
// TODO Auto-generated method stub
return o1.getValue().compareTo(o2.getKey());
}
});
Map sortedMap = new LinkedHashMap();
for(Map.Entry<key, Val> entity: Val){
sortedMap.put(entity.getKey(), entity.getValue());
}
return sortedMap;
}
public static <key extends Comparable,Val extends Comparable> Map<key,Val> customKeySort(Map<key,Val> map){
List<key> list = new ArrayList<key>(map.keySet());
Collections.sort(list,new Comparator<key>() {
@Override
public int compare(key o1, key o2) {
// TODO Auto-generated method stub
return o1.compareTo(o2);
}
});
Map sortedMap = new LinkedHashMap();
for(key k: list){
sortedMap.put(k, map.get(k));
}
return sortedMap;
}}
Sunday, 24 March 2013
How to sort Map by key and value in Java.
Subscribe to:
Posts (Atom)