merge Maps - Java Collection Framework

Java examples for Collection Framework:Map

Description

merge Maps

Demo Code


//package com.java2s;
import java.util.*;

public class Main {
    public static <T> Map<T, Integer> mergeMaps(
            final Map<T, Integer>... maps) {
        final Map<T, Integer> merged = new HashMap<T, Integer>();
        for (final Map<T, Integer> map : maps) {
            for (final Map.Entry<T, Integer> entry : map.entrySet()) {
                if (entry.getValue() != null && entry.getValue() != 0) {
                    final Integer curValue = merged.get(entry.getKey());
                    merged.put(entry.getKey(),
                            curValue == null ? entry.getValue() : curValue
                                    + entry.getValue());
                }/*from   w ww.j  a va2s.c o m*/
            }
        }
        return merged;
    }
}

Related Tutorials