UnmodifiableMapCollector.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.UnmodifiableMap;
  23. import net.morimekta.collect.UnmodifiableSet;

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

  30. public class UnmodifiableMapCollector<E, K, V> implements Collector<E, UnmodifiableMap.Builder<K, V>, UnmodifiableMap<K, V>> {
  31.     private final Function<E, K> toKey;
  32.     private final Function<E, V> toValue;

  33.     public UnmodifiableMapCollector(Function<E, K> toKey, Function<E, V> toValue) {
  34.         this.toKey = toKey;
  35.         this.toValue = toValue;
  36.     }

  37.     @Override
  38.     public Supplier<UnmodifiableMap.Builder<K, V>> supplier() {
  39.         return UnmodifiableMap::newBuilder;
  40.     }

  41.     @Override
  42.     public BiConsumer<UnmodifiableMap.Builder<K, V>, E> accumulator() {
  43.         return (b, e) -> b.put(toKey.apply(e), toValue.apply(e));
  44.     }

  45.     @Override
  46.     public BinaryOperator<UnmodifiableMap.Builder<K, V>> combiner() {
  47.         return (b1, b2) -> b1.putAll(b2.build());
  48.     }

  49.     @Override
  50.     public Function<UnmodifiableMap.Builder<K, V>, UnmodifiableMap<K, V>> finisher() {
  51.         return UnmodifiableMap.Builder::build;
  52.     }

  53.     @Override
  54.     public Set<Characteristics> characteristics() {
  55.         return UnmodifiableSet.setOf();
  56.     }
  57. }