Thursday, 12 March 2020

Combine hashmaps with same type

Below snippet copies multiple maps to other map of same type.
private static <K, V> Map<K, V> combineMaps(Map<K, V>... maps) {
	if (maps == null || maps.length == 0) {
		return Collections.EMPTY_MAP;
	}

	Map<K, V> result = new HashMap<>();

	for (Map<K, V> map : maps) {
		result.putAll(map);
	}
	return result;
}

App.java
package com.sample.app;

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

public class App {

	private static <K, V> Map<K, V> combineMaps(Map<K, V>... maps) {
		if (maps == null || maps.length == 0) {
			return Collections.EMPTY_MAP;
		}

		Map<K, V> result = new HashMap<>();

		for (Map<K, V> map : maps) {
			result.putAll(map);
		}
		return result;
	}

	public static void main(String[] args) {
		Map<Integer, String> map1 = new HashMap() {
			{
				put(1, "Ram");
				put(2, "Rahim");
				put(3, "Joel");
			}
		};

		Map<Integer, String> map2 = new HashMap() {
			{
				put(3, "JaiDeep");
				put(4, "Krishna");
				put(6, "Naveed");
			}
		};

		Map<Integer, String> combinedMap = combineMaps(map1, map2);

		for (int key : combinedMap.keySet()) {
			System.out.println(key + " : " + combinedMap.get(key));
		}
	}

}

Output
1 : Ram
2 : Rahim
3 : JaiDeep
4 : Krishna
6 : Naveed

You may like

No comments:

Post a Comment