Created
December 11, 2018 00:57
-
-
Save Abhishek-Chaudhary-InfoCepts/cb872b6741cab91fbc44643ebb9a0207 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.dojo.java8.tutorials.hashmap; | |
import java.util.Comparator; | |
import java.util.HashMap; | |
import java.util.LinkedHashMap; | |
import java.util.Map; | |
import java.util.stream.Collectors; | |
public class HashMapSortingByValues { | |
public static void main(String[] args) { | |
// create the map of primitives | |
HashMap<Integer, String> empIdVsName = new HashMap<>(); | |
empIdVsName.put(99, "Tom"); | |
empIdVsName.put(5, "Abby"); | |
empIdVsName.put(2, "Sam"); | |
empIdVsName.put(3, "Roger"); | |
empIdVsName.put(7, "Tim"); | |
//empIdVsName.put(null, "Harry"); | |
System.out.println("default output: " + empIdVsName); | |
// sorted api- make use of Map.Entry.comparingByValue | |
LinkedHashMap<Integer, String> empIdVsName_sorted = empIdVsName | |
.entrySet() | |
.stream() | |
.sorted(Map.Entry.comparingByValue()) | |
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, | |
(oldValue, newValue) -> oldValue, LinkedHashMap::new)); | |
System.out.println("sorted by values in asc order: " + empIdVsName_sorted); | |
empIdVsName_sorted = empIdVsName | |
.entrySet() | |
.stream() | |
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) | |
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, | |
(oldValue, newValue) -> oldValue, LinkedHashMap::new)); | |
System.out.println("sorted by values in desc order: " + empIdVsName_sorted); | |
} | |
//output | |
//default output: {2=Sam, 99=Tom, 3=Roger, 5=Abby, 7=Tim} | |
//sorted by values in asc order: {5=Abby, 3=Roger, 2=Sam, 7=Tim, 99=Tom} | |
//sorted by values in desc order: {99=Tom, 7=Tim, 2=Sam, 3=Roger, 5=Abby} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment