Home
Java
Sort HashMap: Keys and Values
This page was last reviewed on Sep 14, 2023.
Dot Net Perls
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.
HashMap
Example. 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.
Step 1 We create a HashMap collection that has 4 keys and a value for each of those keys.
Step 2 We convert the HashMap to an ArrayList by using the addAll() function on the ArrayList.
Collections.addAll
Step 3 We sort the elements in the ArrayList of Entry instances by each key. These are strings, so we call compareTo.
sort
Step 4 With a 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 14, 2023 (new).
Home
Changes
© 2007-2024 Sam Allen.