You cannot have a sorted HashMap
, as is stated in the Javadoc:
... This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
You will have to put it into a different structure that maintains the order you want it to.
Based on what you provided, it looks like you have a few criteria for your order:
- sorted by the
Map.Entry
value, in descending order
- sorted by the
Map.Entry
key, in ascending order
You can make use of the Stream
API, along with the useful Comparator
s from Map.Entry
.
final HashMap<String, Integer> map = new HashMap<>();
map.put("it", 2);
map.put("of", 2);
map.put("the", 2);
map.put("times", 2);
map.put("was", 2);
map.put("best", 1);
map.put("worst", 1);
System.out.println("No Guaranteed Order:");
map.entrySet().stream()
.forEach(System.out::println);
System.out.println();
System.out.println("With Ordering:");
map.entrySet().stream()
.sorted(Map.Entry.<String, Integer>comparingByValue()
.reversed()
.thenComparing(Map.Entry.comparingByKey()))
.forEach(System.out::println);
And the output:
No Guaranteed Order:
the=2
times=2
of=2
was=2
best=1
worst=1
it=2
With Ordering:
it=2
of=2
the=2
times=2
was=2
best=1
worst=1