Advertisement
Guest User

Custom Java 8 Collector

a guest
May 27th, 2015
250
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.06 KB | None | 0 0
  1. public static class MostPopular<T> implements Collector<T, Map<T, Integer>, Optional<T>> {
  2.     @Override
  3.     public Supplier<Map<T, Integer>> supplier() {
  4.         return HashMap::new;
  5.     }
  6.  
  7.     @Override
  8.     public BiConsumer<Map<T, Integer>, T> accumulator() {
  9.         return (acc, elem) -> {
  10.             Integer value = acc.get(elem);
  11.             if (value == null) {
  12.                 value = 1;
  13.             } else {
  14.                 value += 1;
  15.             }
  16.             acc.put(elem, value);
  17.         };
  18.     }
  19.  
  20.     @Override
  21.     public BinaryOperator<Map<T, Integer>> combiner() {
  22.         return (acc1, acc2) -> {
  23.             throw new UnsupportedOperationException();
  24.         };
  25.     }
  26.  
  27.     @Override
  28.     public Function<Map<T, Integer>, Optional<T>> finisher() {
  29.         return (acc) -> acc.entrySet().stream()
  30.                 .reduce((a, b) -> a.getValue() > b.getValue() ? a : b)
  31.                 .map(Map.Entry::getKey);
  32.     }
  33.  
  34.     @Override
  35.     public Set<Characteristics> characteristics() {
  36.         return Collections.emptySet();
  37.     }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement