Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a hash map using key descending order

Tags:

java

How to sort a hash map using key descending order. please explain with example. And how many way to sort a hash map. please explain in details

like image 573
Rahul Avatar asked Jun 15 '15 10:06

Rahul


People also ask

How do you sort HashMap in descending order?

Use the Collections. sort(List) method to sort the list of elements by values by passing customized comparator. Now create a new LinkedHashMap and copy the sorted elements into that. Since LinkedHashMap guarantees the insertion order of mappings.

How do you arrange elements in a Map in descending order?

How to store elements in reverse order or descending order when inserting in map and multimap? We can use the third parameter, that is std::greater along with map and multimap to store elements in descending order.

Can we sort HashMap by key?

Sort HashMap by Keys When we use LinkedHashMap, we should follow the process: When we use LinkedHashMap, then we need to get Key set. Convert the Set into List, sort the list and then add the sorted list into LinkedHashMap in the same order. The same process we have done in the example Sort HashMap by Value.

How do I sort HashMap values?

Our task is to sort the hashmap according to values i.e. according to marks. Solution: The idea is to store the entry set in a list and sort the list on the basis of values. Then fetch values and keys from the list and put them in a new hashmap. Thus, a new hashmap is sorted according to values.


2 Answers

I suggest using this method as included in Java 8.

List<Map.Entry<String, Integer>> sorted_map =
                map_1.entrySet()
                .stream()
                .sorted(reverseOrder(Map.Entry.comparingByKey()))
                .collect(Collectors.toList());

Here 'map_1' is the map you want to sort.

Now you can use the sorted_map variable to iterate and use for your purpose.

Make sure to :

import static java.util.Collections.reverseOrder;
like image 50
Paarth Kotak Avatar answered Oct 13 '22 04:10

Paarth Kotak


HashMaps don't support sorting. They store entries in buckets, how they see it fit, just based on the hashCode value of the keys. They are fine for storing things and looking them up afterwards, but unsuitable for iterating over their contents (which is what you apparently want to do) because you cannot rely on their order and iterating over it is usually expensive.

Try a TreeMap instead. You can specify a custom comparator that does just the reverse of the default comparator. In that case your entries will be ordered in descending order. Collections.reverseOrder will create such a comparator for you, you can use it like this:

new TreeMap<Integer, String>(Collections.reverseOrder());
like image 27
mastov Avatar answered Oct 13 '22 04:10

mastov