How to sort a hashmap
by the integer value and one of the answers that I found is here
that written by Evgeniy Dorofeev and his answer was like this
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("a", 4);
map.put("c", 6);
map.put("b", 2);
Object[] a = map.entrySet().toArray();
Arrays.sort(a, new Comparator() {
public int compare(Object o1, Object o2) {
return ((Map.Entry<String, Integer>) o2).getValue().compareTo(
((Map.Entry<String, Integer>) o1).getValue());
}
});
for (Object e : a) {
System.out.println(((Map.Entry<String, Integer>) e).getKey() + " : "
+ ((Map.Entry<String, Integer>) e).getValue());
}
output
c : 6
a : 4
b : 2
my question is how the sort become Desc ?? and if I want to sort the HashMap
Asc How can I do that ??
and the last question is : How can I have the first element after sorting?
For inverse ordering switch o2
and o1
. For getting the first element just access the array at index 0:
Map<String, Integer> map = new HashMap<>();
map.put("a", 4);
map.put("c", 6);
map.put("b", 2);
Object[] a = map.entrySet().toArray();
Arrays.sort(a, new Comparator() {
public int compare(Object o1, Object o2) {
return ((Map.Entry<String, Integer>) o1).getValue().compareTo(
((Map.Entry<String, Integer>) o2).getValue());
}
});
for (Object e : a) {
System.out.println(((Map.Entry<String, Integer>) e).getKey() + " : "
+ ((Map.Entry<String, Integer>) e).getValue());
}
System.out.println("first element is " + ((Map.Entry<String, Integer>) a[0]).getKey() + " : "
+ ((Map.Entry<String, Integer>) a[0]).getValue());
Which prints
b : 2
a : 4
c : 6
first element is b : 2
If you have access to lambda expression you can simplify the sorting using those:
Arrays.sort(a, (o1, o2) ->
((Map.Entry<String, Integer>) o1).getValue().compareTo(((Map.Entry<String, Integer>) o2).getValue()));
In Java 8, you could do something like:
System.out.println(map.entrySet().stream().sorted((o1, o2) -> {
return o2.getValue().compareTo(o1.getValue());
}).findFirst());//would return entry boxed into optional which you can unbox.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With