In this article we are going to see about Java 8 - How to Sort map by value Example
Java8SortMap.java
Output
Java8SortMap.java
package com.javatutorialcorner.java8; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.stream.Collectors; public class Java8SortMap { public static void main(String[] args) { MapbatsmanRanking = new HashMap (); batsmanRanking.put("Virat Kohli", 1); batsmanRanking.put("AB de Villiers", 2); batsmanRanking.put("David Warner", 3); batsmanRanking.put("Joe Root", 4); batsmanRanking.put("Kane Williamson", 5); batsmanRanking.put("Quinton de Kock", 6); batsmanRanking.put("Faf du Plessis", 7); batsmanRanking.put("Babar Azam", 8); batsmanRanking.put("Martin Guptill", 9); batsmanRanking.put("Shikhar Dhawan", 10); System.out.println("Unsort Map..."); System.out.println(batsmanRanking); //Convert a Map into a Stream //Sort it - values, reserve it and return a new LinkedHashMap //Collect and return a new LinkedHashMap (keep the order) - //toMap() will returns HashMap by default, we need LinkedHashMap to keep the order. Map resultMap1 = batsmanRanking.entrySet().stream() .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new)); Map resultMap2 = new LinkedHashMap<>(); batsmanRanking.entrySet().stream() .sorted(Map.Entry. comparingByValue().reversed()) .forEachOrdered(x -> resultMap2.put(x.getKey(), x.getValue())); System.out.println("Sorted Map 1..."); System.out.println(resultMap1); System.out.println("Sorted Map 2..."); System.out.println(resultMap2); } }
Output
Unsort Map...
{Faf du Plessis=7, Virat Kohli=1, Martin Guptill=9, Babar Azam=8, Quinton de Kock=6, Kane Williamson=5, AB de Villiers=2, Joe Root=4, David Warner=3, Shikhar Dhawan=10}
Sorted Map 1...
{Shikhar Dhawan=10, Martin Guptill=9, Babar Azam=8, Faf du Plessis=7, Quinton de Kock=6, Kane Williamson=5, Joe Root=4, David Warner=3, AB de Villiers=2, Virat Kohli=1}
Sorted Map 2...
{Shikhar Dhawan=10, Martin Guptill=9, Babar Azam=8, Faf du Plessis=7, Quinton de Kock=6, Kane Williamson=5, Joe Root=4, David Warner=3, AB de Villiers=2, Virat Kohli=1}
0 comments:
Post a Comment