Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.util.HashMap;
import java.util.HashSet;

import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;
import javax.annotation.Nonnull;

public class Main {
    /**
     * Returns a Map<V,Set<K>>
     * <p>
     * {@link Supplier} are based on {@link HashMap} and {@link HashSet}
     * <p>
     * Original map is not modify by this operation.
     *
     * @param <K>
     *            The type of the key of the initial map, the type of the value
     *            in result {@link Map}{@link Set}
     * @param <V>
     *            The type of the value of the initial map, the type of the key
     *            in result {@link Map}{@link Set}
     * @param map
     *            The map
     * @return a {@link Map} build using {@link HashMap} {@link HashSet}
     *
     * @see #reverseMap(Map, Supplier, Supplier)
     */
    public static <K, V> Map<V, Set<K>> reverseMap(final Map<K, V> map) {
        final Supplier<Map<V, Set<K>>> mapSupplier = HashMap::new;
        final Supplier<Set<K>> setSupplier = HashSet::new;

        return reverseMap(map, mapSupplier, setSupplier);
    }

    /**
     * Returns a {@link Map}&lt;V,{@link Set}&lt;K&gt;&gt; build by exchange
     * key and value of original {@code map}. All couple (K,V) are kept by
     * this operation.
     * <p>
     * Original map is not modify by this operation.
     *
     * @param <K>
     *            The type of the key of the initial map, the type of the value
     *            in result {@link Map}{@link Set}
     * @param <V>
     *            The type of the value of the initial map, the type of the key
     *            in result {@link Map}{@link Set}
     * @param map
     *            The map
     * @param mapSupplier
     *            The {@link Map} {@link Supplier}
     * @param setSupplier
     *            The {@link Set} {@link Supplier}
     * @return a {@link Map} build using {@link HashMap} {@link Set}
     */
    public static <K, V> Map<V, Set<K>> reverseMap(@Nonnull final Map<K, V> map,
            @Nonnull final Supplier<Map<V, Set<K>>> mapSupplier, @Nonnull final Supplier<Set<K>> setSupplier) {
        final Map<V, Set<K>> reverseMap = mapSupplier.get();

        for (final Map.Entry<K, V> entry : map.entrySet()) {
            final K oldKey = entry.getKey();
            final V oldValue = entry.getValue();
            final Set<K> set;

            if (reverseMap.containsKey(oldValue)) {
                set = reverseMap.get(oldValue);
            } else {
                set = setSupplier.get();

                reverseMap.put(oldValue, set);
            }
            set.add(oldKey);
        }

        return reverseMap;
    }
}