SHARE
TWEET

mapSorter

a guest Jun 25th, 2019 58 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package fr.edu.grenoble.sconet.common.util;
  2.  
  3. import java.util.LinkedHashMap;
  4. import java.util.Map;
  5.  
  6. import lombok.AccessLevel;
  7. import lombok.AllArgsConstructor;
  8. import lombok.EqualsAndHashCode;
  9. import lombok.Getter;
  10. import lombok.NoArgsConstructor;
  11.  
  12. @NoArgsConstructor(access = AccessLevel.NONE)
  13. public final class MapUtils {
  14.  
  15.     public static <A extends Comparable<A>, B extends Comparable<B>> Map<A, B> trierMap(
  16.             final Map<A, B> mapATrier) {
  17.         @AllArgsConstructor
  18.         @EqualsAndHashCode(of = {"a", "b"})
  19.         @Getter
  20.         class ComparableMapEntry<C extends A, D extends B>
  21.                 implements Comparable<ComparableMapEntry<C, D>> {
  22.  
  23.             private final C a;
  24.  
  25.             private final D b;
  26.  
  27.             public ComparableMapEntry(final Map.Entry<C, D> mapEntry) {
  28.                 this(mapEntry.getKey(), mapEntry.getValue());
  29.             }
  30.  
  31.             @Override
  32.             public int compareTo(final ComparableMapEntry<C, D> o) {
  33.                 int compareResult = this.getA().compareTo(o.getA());
  34.                 if (compareResult == 0) {
  35.                     return this.getB().compareTo(o.getB());
  36.                 }
  37.                 return compareResult;
  38.             }
  39.         }
  40.  
  41.         return mapATrier.entrySet()
  42.             .stream()
  43.             .map(ComparableMapEntry::new)
  44.             .sorted()
  45.             .collect(LinkedHashMap::new, (final Map<A, B> map,
  46.                     final ComparableMapEntry<A, B> entry) -> map.put(entry.getA(), entry.getB()),
  47.                     Map::putAll);
  48.     }
  49.  
  50. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top