Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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}
- }
Add Comment
Please, Sign In to add comment