Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Java by (3.5k points)

I am new to Java and generally find that I need to classify a Map<Key, Value> on the values.

Since the values are not unique, I find myself changing the keySet into an array, and classifying that array within array sort with a custom comparator that classifies on the value correlated with the key.

Is there an elementary way?

1 Answer

0 votes
by (46k points)

You can perform this task using the following code:

public class MapUtil

{

   public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map)

{

       List<Entry<K, V>> list = new ArrayList<>(map.entrySet());

       list.sort(Entry.comparingByValue());

       Map<K, V> result = new LinkedHashMap<>();

       for (Entry<K, V> entry : list)

{

           result.put(entry.getKey(), entry.getValue());

       }

       return result;

   }

}

And if you are using JAVA 8 or above, you can use streams API to perform this task:

Map<K, V> sortedMap = map.entrySet().stream()

                        .sorted(Entry.comparingByValue())

                        .collect(Collectors.toMap(Entry::getKey, Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));

To know more about streams API click here.

Related questions

0 votes
1 answer
asked Jul 9, 2019 in Java by Krishna (2.6k points)
0 votes
1 answer
0 votes
1 answer

Browse Categories

...