Java tutorial
/** * The MIT License (MIT) * * Copyright (c) 2015 Georgy Vlasov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.tenidwa.collections.utils; import com.google.common.collect.ForwardingMap; import com.google.common.collect.ImmutableMap; import java.util.Map; import java.util.Set; import java.util.function.Function; /** * A map that augments another map with more values. For every key that is * not in the base map, a key-value pair will be present in the augmented * map, with the value generated by the augmentaiton function. * @author Georgy Vlasov (suseika@tendiwa.org) * @version $Id$ * @since 0.7.0 */ public final class AugmentedMap<K, V> extends ForwardingMap<K, V> { /** * Map delegate. */ private final transient Map<K, V> delegate; /** * Ctor. * @param base Base map to augment. * @param keys Keys of the augmented map. * @param augmentation Function used to generate the new values. */ public AugmentedMap(final Map<K, V> base, final Set<? extends K> keys, final Function<K, V> augmentation) { this.delegate = AugmentedMap.createDelegate(base, keys, augmentation); } /** * Creates map delegate. * @param base Base map to augment. * @param keys Keys to the augmented map. * @param augmentation Function used to generate the new values. * @param <K> Key * @param <V> Value * @return A copy of the {@code base} map augmented with new values. */ private static <K, V> ImmutableMap<K, V> createDelegate(final Map<K, V> base, final Set<? extends K> keys, final Function<K, V> augmentation) { final ImmutableMap.Builder<K, V> builder = ImmutableMap.builder(); builder.putAll(base); keys.stream().filter(key -> !base.containsKey(key)) .forEach(key -> builder.put(key, augmentation.apply(key))); return builder.build(); } @Override protected Map<K, V> delegate() { return this.delegate; } }