Thursday , September 19 2019
Home / Uncategorized / How to sort a map based on the value in Java 8+

How to sort a map based on the value in Java 8+



This was one of the most frequently asked questions in Java interviews. With flows introduced after Java 8, this can be achieved in an elegant and functional way.

For example, consider mapping a word and its corresponding counts into a particular document as shown below:

Final Map wordCounts = new HashMap <> ();
wordCounts.put ("USA", 100);
wordCounts.put ("jobs", 200);
wordCounts.put ("software", 50);
wordCounts.put ("technology", 70);
wordCounts.put ("opportunity", 200);

Now, if I have to sort this map in ascending order, then it would be as simple and readable as below:

Final Map sortedByCount = wordCounts.entrySet ()
.stream ()
.sorted (Map.Entry.comparingByValue ())
.collect (Collectors.toMap (Map.Entry :: getKey, Map.Entry :: getValue, (e1, e2) -> e1, LinkedHashMap :: new));

Here, I'm usingLinkedHashMap to store the ordered result to preserve the order of the elements in the resulting map.

The advantages of this approach are:

  1. It does not modify the original data wordcounts, making it safer.
  2. It is more readable.

If you want to sort a map in reverse order, simply specify the comparison of the value as a reverse order, such as:

Final Map sortedByCount = wordCounts.entrySet ()
.stream ()
.sorted ((Map.Entry.comparingByValue (). reversed ()))
.collect (Collectors.toMap (Map.Entry :: getKey, Map.Entry :: getValue, (e1, e2) -> e1, LinkedHashMap :: new));

The complete program for reverse ordering is:

public class SortMapByValueExample {
static public map sortByValue (final map wordCounts) {

return wordCounts.entrySet ()
.stream ()
.sorted ((Map.Entry.comparingByValue (). reversed ()))
.collect (Collectors.toMap (Map.Entry :: getKey, Map.Entry :: getValue, (e1, e2) -> e1, LinkedHashMap :: new));
}

public static void main (String[] args) {
Final Map wordCounts = new HashMap <> ();
wordCounts.put ("USA", 100);
wordCounts.put ("jobs", 200);
wordCounts.put ("software", 50);
wordCounts.put ("technology", 70);
wordCounts.put ("opportunity", 200);

Final Map sortedByCount = sortByValue (wordCounts);

System.out.println (sortedByCount);
}
}

The output of the program is:

{jobs = 200, opportunity = 200, USA = 100, technology = 70, software = 50}

You can see that the sorted () the method requirescomparator as an argument, making it possible to sort a map with any type of value. For example, the above sort can be written with comparator as:

static public map sortByValue (final map wordCounts) {

return wordCounts.entrySet ()
.stream ()
.sorted ((e1, e2) -> e2.getValue (). compareTo (e1.getValue ()))
.collect (Collectors.toMap (Map.Entry :: getKey, Map.Entry :: getValue, (e1, e2) -> e1, LinkedHashMap :: new));
}

You can implement comparator with any type of object. Is not it an interesting feature?


Source link

Leave a Reply

Your email address will not be published.