I this tutorials, I am going to show you how to sort a Map using Java 8 features.
Sort a Map using Java8 :
We can sort a map by two ways: Sort by key and value.
Sort by key :
package com.onlinetutorialspoint.java8; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; public class Java8_SortaMap { public static void main(String[] args) { Map<String, Integer> marks = new HashMap<>(); marks.put("Maths", 95); marks.put("Chemistry", 84); marks.put("Physics", 92); marks.put("Languages", 94); sortByKey(marks); } public static void sortByKey(Map<String, Integer> marks) { Map<String, Integer> sortedMap = new LinkedHashMap<>(); marks.entrySet().stream() .sorted(Map.Entry.<String, Integer>comparingByKey()) .forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue())); System.out.println(sortedMap); } }
[box type=”success” align=”alignleft” class=”” width=”100%”]
{Chemistry=84, Languages=94, Maths=95, Physics=92}
[/box]
Sort by Value :
package com.onlinetutorialspoint.java8; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; public class Java8_SortaMap { public static void main(String[] args) { Map<String, Integer> marks = new HashMap<>(); marks.put("Maths", 95); marks.put("Chemistry", 84); marks.put("Physics", 92); marks.put("Languages", 94); sortByValue(marks); } public static void sortByValue(Map<String, Integer> marks) { Map<String, Integer> sortedMap = new LinkedHashMap<>(); marks.entrySet().stream() .sorted(Map.Entry.<String, Integer>comparingByValue().reversed()) .forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue())); System.out.println(sortedMap); } }
[box type="success" align="alignleft" class="" width="100%"] {Maths=95, Languages=94, Physics=92, Chemistry=84} [/box]
Leave A Comment