package org.zwobble.mammoth.internal.util; import com.google.common.collect.ImmutableMap; import java.util.*; import java.util.function.Function; public class MammothMaps { public static Map map() { return ImmutableMap.of(); } public static Map map(K key1, V value1) { return ImmutableMap.of(key1, value1); } public static Map map(K key1, V value1, K key2, V value2) { return ImmutableMap.of(key1, value1, key2, value2); } public static Map map(K key1, V value1, K key2, V value2, K key3, V value3) { return ImmutableMap.of(key1, value1, key2, value2, key3, value3); } public static Map.Entry entry(K key, V value) { return new AbstractMap.SimpleImmutableEntry(key, value); } public static Optional lookup(Map map, K key) { return Optional.ofNullable(map.get(key)); } public static Map toMapWithKey(Iterable iterable, Function function) { return toMap(iterable, element -> entry(function.apply(element), element)); } public static Map toMap(Iterable iterable, Function> function) { ImmutableMap.Builder builder = ImmutableMap.builder(); for (T element : iterable) { builder.put(function.apply(element)); } return builder.build(); } public static Map> toMultiMapWithKey(Iterable iterable, Function function) { return toMultiMap(iterable, element -> entry(function.apply(element), element)); } public static Map> toMultiMap(Iterable iterable, Function> function) { Map> map = new HashMap<>(); for (T element : iterable) { Map.Entry pair = function.apply(element); map.computeIfAbsent(pair.getKey(), key -> new ArrayList()) .add(pair.getValue()); } return map; } public static Map eagerMapValues(Map map, Function function) { Map result = new HashMap<>(); for (Map.Entry element : map.entrySet()) { result.put(element.getKey(), function.apply(element.getValue())); } return result; } }