All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.dongliu.commons.lang.collection.Maps Maven / Gradle / Ivy

There is a newer version: 2.1.5
Show newest version
package net.dongliu.commons.lang.collection;

import java.util.*;

/**
 * utils method for map
 *
 * @author Dong Liu
 */
public class Maps {

    /**
     * get map, from multi key-value pair.
     * 
     * {@code Map map = Maps.of(
     *     Pair.of("test", 1),
     *     Pair.of("test2", 2),
     *     Pair.of("test3", 3)
     * );
     * }
     * 
* * @param pairs key-value list */ @SafeVarargs public static Map of(Pair... pairs) { Map map = new HashMap<>(); for (Pair pair : pairs) { map.put(pair.getKey(), pair.getValue()); } return map; } /** * get map, from multi key-value pair. *
     * {@code
     * Map; map = Maps.of(
     *     Lists.of(Pair.of("test", 1), Pair.of("test2", 2), Pair.of("test3", 3))
     * );
     * }
     * 
* * @param pairs key-value list */ public static Map of(Collection> pairs) { Map map = new HashMap<>(); for (Pair pair : pairs) { map.put(pair.getKey(), pair.getValue()); } return map; } /** * get immutable map * * @param map the mutable map */ public static Map immutable(Map map) { return Collections.unmodifiableMap(map); } /** * get map by key collection and value collection. *
     * {@code
     * Map map = Maps.zip(
     *     Lists.of("test", "test2", "test3"),
     *     Lists.of(1, 2, 3)
     * );
     * }
     * 
* * @return map */ public static Map zip(Collection keys, Collection values) { if (keys.size() != values.size()) { throw new IllegalArgumentException("size of keys not equals size of values"); } Iterator keyIt = keys.iterator(); Iterator valueIt = values.iterator(); Map map = new HashMap<>(); while (keyIt.hasNext()) { map.put(keyIt.next(), valueIt.next()); } return map; } /** * get map by key array and value array. *
     * {@code
     * Map map = Maps.zip(
     *     Arrays.of("test", "test2", "test3"),
     *     Arrays.of(1, 2, 3)
     * );
     * }
     * 
* * @return map */ public static Map zip(S[] keys, T[] values) { if (keys.length != values.length) { throw new IllegalArgumentException("size of keys not equals size of values"); } Map map = new HashMap<>(); for (int i = 0; i < keys.length; i++) { map.put(keys[i], values[i]); } return map; } }