Sort a Map<Key, Value> by values (Java)
My question is different from the above. I want to count the number of occurrences of values of key and sort both keys and values in descending order.
I have this hash map:
0=[1, 2], 1=[2, 3], 2=[4], 3=[4, 5], 4=[5], 5=[]
I want to have a list of keys and values sorted in descending order based on the count of values it has. The final list should be
0=[1, 2], 1=[3, 2], 3=[4,5], 2=[4], 4=[5], 5=[]
The keys and values should be arranged based on following : 0 has two values, 1 has two values, 3 has two values, 2 has one value, 4 has one value and 5 has nothing so on..
Note: both keys and values both are arranged based on the count.
I just sorted the keys based on the count of values
Map<Integer, Integer> map_degree = new HashMap<Integer, Integer>();
for (Entry<Integer, ArrayList<Integer>> entry : list.entrySet()) {
ArrayList<Integer> value=entry.getValue();
int degree= value.size();
int key=entry.getKey();
map_degree.put(key,degree);
}
System.out.println("The mapping"+list);
System.out.println("Before sorting" + map_degree);
System.out.println("After sorting descindeng order");
Map<Integer, Integer> sortedVertex = sortByComparator(map_degree);
System.out.println(sortedVertex);
}
private static Map<Integer, Integer> sortByComparator(Map<Integer, Integer> map_degree)
{
LinkedList<Entry<Integer, Integer>> list_sorting = new LinkedList<Entry<Integer, Integer>>(map_degree.entrySet());
// Sorting the list based on values
Collections.sort(list_sorting, new Comparator<Entry<Integer, Integer>>()
{
public int compare(Entry<Integer, Integer> o1,
Entry<Integer, Integer> o2)
{
{
// returns descending order
return o2.getValue().compareTo(o1.getValue());
}
}
});
// Maintaining insertion order with the help of LinkedList
Map<Integer, Integer> sortedMap = new LinkedHashMap<Integer, Integer>();
for (Entry<Integer, Integer> entry : list_sorting)
{
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
The output is (key is sorted and mapped with count of values)
Before sorting{0=2, 1=2, 2=1, 3=2, 4=1, 5=0}
After sorting descindeng order
{0=2, 1=2, 3=2, 2=1, 4=1, 5=0}
How can i order the values of the key also such that finally i get
0=[1, 2], 1=[3, 2], 3=[4,5], 2=[4], 4=[5], 5=[] ?