Treemap Sort by Value

TreeMap sort by value

You can't have the TreeMap itself sort on the values, since that defies the SortedMap specification:

A Map that further provides a total ordering on its keys.

However, using an external collection, you can always sort Map.entrySet() however you wish, either by keys, values, or even a combination(!!) of the two.

Here's a generic method that returns a SortedSet of Map.Entry, given a Map whose values are Comparable:

static <K,V extends Comparable<? super V>>
SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map) {
SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
new Comparator<Map.Entry<K,V>>() {
@Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
int res = e1.getValue().compareTo(e2.getValue());
return res != 0 ? res : 1;
}
}
);
sortedEntries.addAll(map.entrySet());
return sortedEntries;
}

Now you can do the following:

    Map<String,Integer> map = new TreeMap<String,Integer>();
map.put("A", 3);
map.put("B", 2);
map.put("C", 1);

System.out.println(map);
// prints "{A=3, B=2, C=1}"
System.out.println(entriesSortedByValues(map));
// prints "[C=1, B=2, A=3]"

Note that funky stuff will happen if you try to modify either the SortedSet itself, or the Map.Entry within, because this is no longer a "view" of the original map like entrySet() is.

Generally speaking, the need to sort a map's entries by its values is atypical.


Note on == for Integer

Your original comparator compares Integer using ==. This is almost always wrong, since == with Integer operands is a reference equality, not value equality.

    System.out.println(new Integer(0) == new Integer(0)); // prints "false"!!!

Related questions

  • When comparing two Integers in Java does auto-unboxing occur? (NO!!!)
  • Is it guaranteed that new Integer(i) == i in Java? (YES!!!)

How to sort a treemap based on its values?

You cannot as the TreeMap's comparator is run against the keys only, e.g. see this constructor.

Anyway, you can use multiple Collections, use the TreeMap (or rather HashMap) for looking up elements by keys, and have a SortedSet to iterate on the values.

Sorting TreeMaps by value

Set up a second TreeMap, using the customers last name as the key:

TreeMap<String,Customer> sortByName  = new TreeMap<>();
TreeMap<Long,Customer> sortByID = new TreeMap<>();
----------------
sortByName.put(customer.getLastName(), customer);
sortByID.put(new Long(customer.getID()), customer);
----------------
return sortByName.values().toArray( new Customer[sortByName.size()] );
'''

How to sort a treemap key that is a String according to a given set of comparator in Java

If you change your Map to Map<Integer, Collection<UserHistoryDto>> and change map.put(day, col) to map.put(date, col), you'll get the sorting you want (assuming Monday has the lowest numeric value).

If you must keep the current Map structure, you can pass a Comparator<String> to the constructor of the TreeMap. That Comparator's compare() method will have to map each String value to a corresponding numeric value and compare those values (for example, "Monday" will be mapped to 1, "Tuesday" to 2, and so on...).

Here's one way of creating the Comparator. It requires first creating a Map that maps day Strings into integer values.

Map<String,Integer> dayValues = new HashMap<>();
dayValues.put("Monday",1);
...
dayValues.put("Sunday",7);
Comparator<String> cmpDays = Comparator.comparing(dayValues::get);
...
Map<String, Collection<UserHistoryDto>> map = new TreeMap<>(cmpDays);

are the values in a treeMap sorted: java

It is sorted: Treemap.values()

The collection's iterator returns the values in ascending order of the corresponding keys.



Related Topics



Leave a reply



Submit