Returns a new map with all entries of the input map except those which have a value of null. - Java Collection Framework

Java examples for Collection Framework:Map

Description

Returns a new map with all entries of the input map except those which have a value of null.

Demo Code


//package com.java2s;

import java.util.HashMap;

import java.util.Map;

public class Main {
    /**/* w w w  .ja  v  a  2  s  .c om*/
     * Returns a new map with all entries of the input map except those which have a value of null.<p>
     * 
     * @param <A> the key type of the map
     * @param <B> the value type of the map 
     * @param map the input map
     *  
     * @return a map with all null entries removed 
     */
    public static <A, B> Map<A, B> removeNullEntries(Map<A, B> map) {

        HashMap<A, B> result = new HashMap<A, B>();

        for (Map.Entry<A, B> entry : map.entrySet()) {
            if (entry.getValue() != null) {
                result.put(entry.getKey(), entry.getValue());
            }
        }
        return result;
    }
}

Related Tutorials