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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.