io.github.carlomicieli.footballdb.starter.utils.MapUtils.java Source code

Java tutorial

Introduction

Here is the source code for io.github.carlomicieli.footballdb.starter.utils.MapUtils.java

Source

/*
 * Copyright 2014 the original author or authors.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package io.github.carlomicieli.footballdb.starter.utils;

import org.apache.commons.lang3.tuple.ImmutablePair;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Utility methods for Maps.
 *
 * @author Carlo Micieli
 */
public interface MapUtils {

    /**
     * Creates a new immutable map from the pair available in the provided stream.
     * @param pairs
     * @param <K>
     * @param <V>
     * @return
     */
    public static <K, V> Map<K, V> newMap(Stream<ImmutablePair<K, V>> pairs) {
        return Collections
                .unmodifiableMap(pairs.collect(Collectors.toMap(ImmutablePair::getLeft, ImmutablePair::getRight)));
    }

    public static <K, V> Map<K, V> asMap(K k, V v) {
        Map<K, V> m = new HashMap<>();
        m.put(k, v);
        return Collections.unmodifiableMap(m);
    }

    public static <K, V> ImmutablePair<K, V> pair(K k, V v) {
        return ImmutablePair.of(k, v);
    }

}