Copies entries from one map to another and deletes those entries in the target map for which the value in the source map is null. - Java Collection Framework

Java examples for Collection Framework:Map

Description

Copies entries from one map to another and deletes those entries in the target map for which the value in the source map is null.

Demo Code


//package com.java2s;

import java.util.Map;

public class Main {
    /**//from   w  w  w  .j  ava 2  s  . co  m
     * Copies entries from one map to another and deletes those entries in the target map for which
     * the value in the source map is null.<p>
     * 
     * @param <A> the key type of the map 
     * @param <B> the value type of the map 
     * @param source the source map
     * @param target the target map 
     */
    public static <A, B> void updateMapAndRemoveNulls(Map<A, B> source,
            Map<A, B> target) {

        assert source != target;
        for (Map.Entry<A, B> entry : source.entrySet()) {
            A key = entry.getKey();
            B value = entry.getValue();
            if (value != null) {
                target.put(key, value);
            } else {
                target.remove(key);
            }
        }
    }
}

Related Tutorials