HashMap doesnt maintain any order, so if you want any kind of ordering, you need to store that in something else, which is a map and can have some kind of ordering, like LinkedHashMap
below is a simple program, by which you can sort by key, value, ascending ,descending ..( if you modify the compactor, you can use any kind of ordering, on keys and values)
package com.edge.collection.map;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class SortMapByKeyValue {
Map map = new HashMap();
public static void main(String[] args) {
SortMapByKeyValue smkv = new SortMapByKeyValue();
smkv.createMap();
System.out.println("After sorting by key ascending order......");
smkv.sortByKey(true);
System.out.println("After sorting by key descindeng order......");
smkv.sortByKey(false);
System.out.println("After sorting by value ascending order......");
smkv.sortByValue(true);
System.out.println("After sorting by value descindeng order......");
smkv.sortByValue(false);
}
void createMap() {
map.put("B", 55);
map.put("A", 80);
map.put("D", 20);
map.put("C", 70);
map.put("AC", 70);
map.put("BC", 70);
System.out.println("Before sorting......");
printMap(map);
}
void sortByValue(boolean order) {
List> list = new LinkedList>(map.entrySet());
Collections.sort(list, new Comparator>() {
public int compare(Entry o1, Entry o2) {
if (order) {
return o1.getValue().compareTo(o2.getValue());
} else {
return o2.getValue().compareTo(o1.getValue());
}
}
});
Map sortedMap = new LinkedHashMap();
for (Entry entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
printMap(sortedMap);
}
void sortByKey(boolean order) {
List> list = new LinkedList>(map.entrySet());
Collections.sort(list, new Comparator>() {
public int compare(Entry o1, Entry o2) {
if (order) {
return o1.getKey().compareTo(o2.getKey());
} else {
return o2.getKey().compareTo(o1.getKey());
}
}
});
Map sortedMap = new LinkedHashMap();
for (Entry entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
printMap(sortedMap);
}
public void printMap(Map map) {
// System.out.println(map);
for (Entry entry : map.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
}
here is the git link