Create unmodifiable Map from Map - Java Collection Framework

Java examples for Collection Framework:Map

Description

Create unmodifiable Map from Map

Demo Code


//package com.java2s;

import java.util.Collections;
import java.util.HashMap;

import java.util.Map;
import java.util.Map.Entry;

public class Main {
    public static void main(String[] argv) {
        System.out.println(map());
    }/*from ww w  .  j a  va  2  s.com*/

    /**
     * @param entries the <i>final</i> set of entries to add to the newly created <i>unmodifiable</i> map
     * @return an <i>unmodifiable</i> map with all given entries
     */
    public static <K, V> Map<K, V> map(final Entry<K, V>... entries) {
        final HashMap<K, V> map = new HashMap<K, V>(entries.length);
        for (final Entry<K, V> entry : entries) {
            map.put(entry.getKey(), entry.getValue());
        }
        return Collections.unmodifiableMap(map);
    }

    public static <K, V> Map<K, V> map() {
        return new HashMap<K, V>();
    }

    /**
     * @return an <b>UNMODIFIABLE</b> Map&lt;K, V&gt;
     */
    public static <K, V> Map<K, V> unmodifiableMap(
            final Map<? extends K, ? extends V> m) {
        return (m == null) ? Collections.<K, V> emptyMap() : Collections
                .unmodifiableMap(m);
    }
}

Related Tutorials