C
C
click_f2016-10-19 14:14:36
Java
click_f, 2016-10-19 14:14:36

How to sort HashMap?

There is HashMap<K, V>, where V is an object containing fields, so it is necessary to sort the hashmap by one of these fields so that the value of the keys corresponds to the order.
Tried to sort through treeMap and custom comparator. Sorted, but faced with the problem that there is an order, but it is not known how to set the value of the keys in the order of storage in treeMap'e. Yes, and I do not need to store in treeMap'e. It seems stupid, crooked and there is a much easier way to do it.
UPD2:

public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
    return map.entrySet()
              .stream()
              .sorted(Map.Entry.comparingByValue(Collections.reverseOrder()))
              .collect(Collectors.toMap(
                Map.Entry::getKey, 
                Map.Entry::getValue,<?>как тут вытащить поле объекта типа V </?> 
                (e1, e2) -> e1, 
                LinkedHashMap::new
              ));
}

Thanks for any advice.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Cheremisin, 2016-10-19
@click_f

TreeMap (SortedMap interface) to help you - https://examples.javacodegeeks.com/core-java/util/...
and http://info.javarush.ru/translation/2014/02/11/9-g ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question