Sort Hashmap keys using numeric value descending

How can I sort HashMap keys by their numeric value? Currently, in natural order, it looks like this:

 1 10 13 2 26 29 

I want it to look like this:

 29 26 13 10 2 1 

Any ideas?

+4
source share
5 answers

A HashMap cannot be sorted. If you need sorted keys, see TreeMap . To get the reverse order you need, you need to provide a custom Comparator :

 class ReversedOrdering implements Comparator<Integer> { public int compare(Integer lhs, Integer rhs) { // compare reversed return rhs.compareTo(lhs); } } 

Edit I just stumbled upon Collections.reverseOrder() , which does exactly what you want: it gives you a Comparator that changes the natural order of objects that implement Comparable . This will save you the hassle of writing a comparator yourself.

+10
source

You can use TreeMap and then call descendingMap () , which basically returns a map with the reverse order of keys

+6
source

HashMap does not sort anything. Use TreeMap if you want to keep the key sorting.

0
source

You can use TreeMap with a constructor that allows you to specify a Comparator .

0
source

Try using the code below, it works fine and based on the order flag will be sorted in ascending or descending order.

 import java.util.Comparator; import java.util.Map; import java.util.TreeMap; /** * @author Rais.Alam * @date Dec 12, 2012 */ public class HelloWorld { public static void main(String[] args) { final boolean order = true; try { Map<Integer, String> map = new TreeMap<Integer, String>( new Comparator<Integer>() { @Override public int compare(Integer first, Integer second) { if (order) { return second.compareTo(first); } else { return first.compareTo(second); } } }); map.put(2, "v"); map.put(3, "h"); map.put(4, "e"); map.put(1, "a"); System.out.println(map); } catch (Exception e) { e.printStackTrace(); } } } 
0
source

Source: https://habr.com/ru/post/1369449/


All Articles