In this article we are going to see about Java 8 - How to Sort map by Key Example
Java8SortMap.java
Output
Java8SortMap.java
package com.javatutorialcorner.java8; 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 - sort by keys 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.comparingByKey()) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new)); Map resultMap2 = new LinkedHashMap<>(); batsmanRanking.entrySet().stream() .sorted(Map.Entry.comparingByKey()) .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...
{AB de Villiers=2, Babar Azam=8, David Warner=3, Faf du Plessis=7, Joe Root=4, Kane Williamson=5, Martin Guptill=9, Quinton de Kock=6, Shikhar Dhawan=10, Virat Kohli=1}
Sorted Map 2...
{AB de Villiers=2, Babar Azam=8, David Warner=3, Faf du Plessis=7, Joe Root=4, Kane Williamson=5, Martin Guptill=9, Quinton de Kock=6, Shikhar Dhawan=10, Virat Kohli=1}
0 comments:
Post a Comment