UnmodifiableSortedMapCollector.java

  1. /*
  2.  * Copyright 2020 Collect Utils Authors
  3.  *
  4.  * Licensed to the Apache Software Foundation (ASF) under one
  5.  * or more contributor license agreements. See the NOTICE file
  6.  * distributed with this work for additional information
  7.  * regarding copyright ownership. The ASF licenses this file
  8.  * to you under the Apache License, Version 2.0 (the
  9.  * "License"); you may not use this file except in compliance
  10.  * with the License. You may obtain a copy of the License at
  11.  *
  12.  *   http://www.apache.org/licenses/LICENSE-2.0
  13.  *
  14.  * Unless required by applicable law or agreed to in writing,
  15.  * software distributed under the License is distributed on an
  16.  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17.  * KIND, either express or implied. See the License for the
  18.  * specific language governing permissions and limitations
  19.  * under the License.
  20.  */
  21. package net.morimekta.collect.collectors;

  22. import net.morimekta.collect.UnmodifiableSet;
  23. import net.morimekta.collect.UnmodifiableSortedMap;

  24. import java.util.Comparator;
  25. import java.util.Set;
  26. import java.util.function.BiConsumer;
  27. import java.util.function.BinaryOperator;
  28. import java.util.function.Function;
  29. import java.util.function.Supplier;
  30. import java.util.stream.Collector;

  31. public class UnmodifiableSortedMapCollector<E, K, V> implements Collector<E, UnmodifiableSortedMap.Builder<K, V>, UnmodifiableSortedMap<K, V>> {
  32.     private final Function<E, K> toKey;
  33.     private final Function<E, V> toValue;
  34.     private final Comparator<? super K>  comparator;

  35.     public UnmodifiableSortedMapCollector(Function<E, K> toKey, Function<E, V> toValue, Comparator<? super K> comparator) {
  36.         this.toKey = toKey;
  37.         this.toValue = toValue;
  38.         this.comparator = comparator;
  39.     }

  40.     @Override
  41.     @SuppressWarnings("unchecked")
  42.     public Supplier<UnmodifiableSortedMap.Builder<K, V>> supplier() {
  43.         return () -> (UnmodifiableSortedMap.Builder<K, V>) UnmodifiableSortedMap.newBuilderOrderedBy(comparator);
  44.     }

  45.     @Override
  46.     public BiConsumer<UnmodifiableSortedMap.Builder<K, V>, E> accumulator() {
  47.         return (b, e) -> b.put(toKey.apply(e), toValue.apply(e));
  48.     }

  49.     @Override
  50.     public BinaryOperator<UnmodifiableSortedMap.Builder<K, V>> combiner() {
  51.         return (b1, b2) -> b1.putAll(b2.build());
  52.     }

  53.     @Override
  54.     public Function<UnmodifiableSortedMap.Builder<K, V>, UnmodifiableSortedMap<K, V>> finisher() {
  55.         return UnmodifiableSortedMap.Builder::build;
  56.     }

  57.     @Override
  58.     public Set<Characteristics> characteristics() {
  59.         return UnmodifiableSet.setOf(Characteristics.UNORDERED);
  60.     }
  61. }