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
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 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.
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.
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.
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;
HashMap
s 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());
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