Created
December 11, 2018 00:57
-
-
Save Abhishek-Chaudhary-InfoCepts/ddbbdf1277915436ad533feca75b474c 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.Map; | |
import java.util.stream.Collectors; | |
import java.util.Comparator; | |
import java.util.HashMap; | |
import java.util.LinkedHashMap; | |
public class HashMapSortingByKeys { | |
public static void main(String[] args) { | |
// create the map of primitives | |
HashMap<Integer, String> empIdVsName = new HashMap<>(); | |
empIdVsName.put(99, "Tom"); | |
empIdVsName.put(5, "Tom"); | |
empIdVsName.put(2, "Sam"); | |
empIdVsName.put(3, "Roger"); | |
empIdVsName.put(7, "Tim"); | |
//empIdVsName.put(null, "Harry"); | |
System.out.println("default output: " + empIdVsName); | |
// asc sort by keys | |
// note that you need to create a new linkedhashmap to get desired sorting order | |
// sorted api- make use of Map.Entry.comparingByKey | |
Map<Integer, String> empIdVsName_sorted = empIdVsName | |
.entrySet() | |
.stream() | |
.sorted(Map.Entry.comparingByKey()) | |
.collect(Collectors.toMap | |
(Map.Entry::getKey, | |
//keymapper | |
Map.Entry::getValue, | |
//valuemapper | |
(oldValue, newValue) -> oldValue, | |
// merge function (optional, based on your data/needs)- | |
//logic that decided what needs to be in case there | |
// are two same keys mappd with different values | |
LinkedHashMap::new) | |
// map supplier (Map into which the results will be inserted) | |
); | |
System.out.println("sorted by keys in asc order: " + empIdVsName_sorted); | |
// desc sort by keys | |
empIdVsName_sorted = empIdVsName | |
.entrySet() | |
.stream() | |
.sorted(Map.Entry.comparingByKey(Comparator.reverseOrder())) | |
.collect(Collectors.toMap | |
(Map.Entry::getKey, | |
//keymapper | |
Map.Entry::getValue, | |
//valuemapper | |
(oldValue, newValue) -> oldValue, | |
// merge function (optional, based on your data/needs)- | |
//logic that decided what needs to be in case there | |
// are two same keys mappd with different values | |
LinkedHashMap::new) | |
// map supplier (Map into which the results will be inserted) | |
); | |
System.out.println("sorted by keys in dec order: " + empIdVsName_sorted); | |
} | |
//default output: {2=Sam, 99=Tom, 3=Roger, 5=Tom, 7=Tim} | |
//sorted by keys in asc order: {2=Sam, 3=Roger, 5=Tom, 7=Tim, 99=Tom} | |
//sorted by keys in dec order: {99=Tom, 7=Tim, 5=Tom, 3=Roger, 2=Sam} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment