Didart

Sorting map by key/value ascending and descending

Nov 7th, 2021
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.64 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. import static java.util.Map.Entry.comparingByKey;
  4. import static java.util.Map.Entry.comparingByValue;
  5. import static java.util.stream.Collectors.toMap;
  6.  
  7. public class demo {
  8.     public static void main(String[] args) {
  9.  
  10.  
  11.         //Map<Integer,Integer>
  12.         Map<Integer, Integer> map1 = new HashMap<>();
  13.  
  14.         // sorted by asc keys
  15.         map1
  16.                 .entrySet()
  17.                 .stream()
  18.                 .sorted(comparingByKey())
  19.                 .collect(
  20.                         toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2,
  21.                                 HashMap::new));
  22.  
  23.         // sorted by desc keys
  24.         map1
  25.                 .entrySet()
  26.                 .stream()
  27.                 .sorted(Collections.reverseOrder(comparingByKey()))
  28.                 .collect(
  29.                         toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2,
  30.                                 HashMap::new));
  31.  
  32.         //sort аsc order of value
  33.         map1
  34.                 .entrySet()
  35.                 .stream()
  36.                 .sorted(comparingByValue())
  37.                 .collect(
  38.                         toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2,
  39.                                 LinkedHashMap::new));
  40.  
  41.         // sort desc order of value
  42.         map1
  43.                 .entrySet()
  44.                 .stream()
  45.                 .sorted(Collections.reverseOrder(comparingByValue()))
  46.                 .collect(
  47.                         toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2,
  48.                                 LinkedHashMap::new));
  49.  
  50.  
  51.     }
  52.  
  53. }
  54.  
Advertisement
Add Comment
Please, Sign In to add comment