Sort
HashMap
It is not possible in Java to sort a HashMap
directly, as the data is not ordered. But we can convert the HashMap
to another type and then sort and display it.
With a lambda expression, we can elegantly sort Entry elements from the original HashMap
. These can be ordered by keys or values.
To begin, we must import several types into the Java program so that it will compile correctly. We perform all the work in the main()
method.
HashMap
collection that has 4 keys and a value for each of those keys.HashMap
to an ArrayList
by using the addAll()
function on the ArrayList
.ArrayList
of Entry instances by each key. These are strings, so we call compareTo
.for
-loop, we display all the results. The string
"ant" is alphabetically first, and "human" is last.import java.util.ArrayList; import java.util.Collections; import java.util.Map.Entry; import java.util.HashMap; public class Program { public static void main(String[] args) { // Step 1: create HashMap. var map = new HashMap<String, Integer>(); map.put("bird", 10); map.put("cat", 200); map.put("ant", 1); map.put("human", 0); // Step 2: convert to list. ArrayList<Entry<String, Integer>> array = new ArrayList<>(); array.addAll(map.entrySet()); // Step 3: sort elements by key with lambda. Collections.sort(array, (a, b) -> a.getKey().compareTo(b.getKey())); // Step 4: display all results. for (Entry<String, Integer> entry : array) { System.out.println(entry); } } }ant=1 bird=10 cat=200 human=0
Though it is not possible to sort a HashMap
directly, we can sort an ArrayList
containing the same data. This can provide the same effect, and is a useful technique.