Create a map from a list of key, value pairs. - Android Phone

Android examples for Phone:Airplane Mode

Description

Create a map from a list of key, value pairs.

Demo Code

/**/*from   w ww . ja  va 2s  .  c  om*/
 * (c) Winterwell Associates Ltd, used under MIT License. This file is background IP.
 */
//package com.java2s;

import java.util.HashMap;

import java.util.Map;

public class Main {
    /**
     * Create a map from a list of key, value pairs. An easy way to make small
     * maps, basically the equivalent of {@link Arrays#asList(Object...)}. If
     * the value is null, the key will not be included.
     */
    public static <K, V> Map<K, V> asMap(Object... keyValuePairs) {
        assert keyValuePairs.length % 2 == 0;
        Map m = new HashMap(keyValuePairs.length / 2);
        for (int i = 0; i < keyValuePairs.length; i += 2) {
            Object v = keyValuePairs[i + 1];
            if (v == null) {
                continue;
            }
            m.put(keyValuePairs[i], v);
        }
        return m;
    }
}

Related Tutorials