Guest User

Untitled

a guest
Dec 10th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. package com.dojo.java8.tutorials.hashmap;
  2.  
  3. import java.util.Map;
  4. import java.util.stream.Collectors;
  5. import java.util.Comparator;
  6. import java.util.HashMap;
  7. import java.util.LinkedHashMap;
  8.  
  9. public class HashMapSortingByKeys {
  10.  
  11. public static void main(String[] args) {
  12.  
  13. // create the map of primitives
  14. HashMap<Integer, String> empIdVsName = new HashMap<>();
  15. empIdVsName.put(99, "Tom");
  16. empIdVsName.put(5, "Tom");
  17. empIdVsName.put(2, "Sam");
  18. empIdVsName.put(3, "Roger");
  19. empIdVsName.put(7, "Tim");
  20. //empIdVsName.put(null, "Harry");
  21.  
  22. System.out.println("default output: " + empIdVsName);
  23.  
  24. // asc sort by keys
  25. // note that you need to create a new linkedhashmap to get desired sorting order
  26. // sorted api- make use of Map.Entry.comparingByKey
  27. Map<Integer, String> empIdVsName_sorted = empIdVsName
  28. .entrySet()
  29. .stream()
  30. .sorted(Map.Entry.comparingByKey())
  31. .collect(Collectors.toMap
  32. (Map.Entry::getKey,
  33. //keymapper
  34. Map.Entry::getValue,
  35. //valuemapper
  36. (oldValue, newValue) -> oldValue,
  37. // merge function (optional, based on your data/needs)-
  38. //logic that decided what needs to be in case there
  39. // are two same keys mappd with different values
  40. LinkedHashMap::new)
  41. // map supplier (Map into which the results will be inserted)
  42. );
  43.  
  44. System.out.println("sorted by keys in asc order: " + empIdVsName_sorted);
  45.  
  46. // desc sort by keys
  47. empIdVsName_sorted = empIdVsName
  48. .entrySet()
  49. .stream()
  50. .sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
  51. .collect(Collectors.toMap
  52. (Map.Entry::getKey,
  53. //keymapper
  54. Map.Entry::getValue,
  55. //valuemapper
  56. (oldValue, newValue) -> oldValue,
  57. // merge function (optional, based on your data/needs)-
  58. //logic that decided what needs to be in case there
  59. // are two same keys mappd with different values
  60. LinkedHashMap::new)
  61. // map supplier (Map into which the results will be inserted)
  62. );
  63.  
  64. System.out.println("sorted by keys in dec order: " + empIdVsName_sorted);
  65. }
  66.  
  67. //default output: {2=Sam, 99=Tom, 3=Roger, 5=Tom, 7=Tim}
  68. //sorted by keys in asc order: {2=Sam, 3=Roger, 5=Tom, 7=Tim, 99=Tom}
  69. //sorted by keys in dec order: {99=Tom, 7=Tim, 5=Tom, 3=Roger, 2=Sam}
  70.  
  71. }
Add Comment
Please, Sign In to add comment