Sort Java HashMap by Value
Here in this example I will show you how to sort a HashMap by value. I will use comparator interface to sort the values in HashMap.
The elements in the HashMap are first converted into LinkedList.
Then I have usedsort() method of Collections API to sort the elements. I have used compareToIgnoreCase() method to ignore the capital or small letters in the string. You can also use compareTo() method to consider the upper or lower case letters.Finally the sorted elements are stored into LinkedHashMap so that their orders are maintained while stored.
The following source code shows how to sort a HashMap by its values:
package com.roytuts.javasort.hashmap.byvalue;
import java.util.Collections;
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 App {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(1, "c");
map.put(2, "b");
map.put(3, "a");
map.put(4, "hi");
map.put(5, "Hi");
map.put(6, "hello");
map.put(7, "Hello");
List<Entry<Integer, String>> list = new LinkedList<>(map.entrySet());
Collections.sort(list, (l1, l2) -> l1.getValue().compareToIgnoreCase(l2.getValue()));
Map<Integer, String> sortedMap = new LinkedHashMap<>();
for (Entry<Integer, String> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
for (Entry<Integer, String> entry : sortedMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
} The output of the above program is given below:
3: a
2: b
1: c
6: hello
7: Hello
4: hi
5: Hi
No comments