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.
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.