Map合并方式方法

	/**
	 * 把Map中Key相同,则各个value添加到一起,汇总值
	 * 把partMap数据合并放到resultMap中。
	 * @param resultMap
	 * @param partMap
	 */
	public static <T, F, K extends Collection<F>> Map merge2ResultMap(Map<T, K> resultMap, Map<T, K> partMap) {
		for (Map.Entry<T, K> entry : partMap.entrySet()) {
			T key = entry.getKey();
			if (resultMap.containsKey(key)) {
				resultMap.get(key).addAll(entry.getValue());
			} else {
				resultMap.putAll(partMap);
			}
		}
		return resultMap;
	}

	/**
	 * 把Map中Key相同,则value相加,值得相加
	 * @param target
	 * @param plus
	 * @return
	 */
	public static Map addTo(Map<String,Double> target, Map<String,Double>plus) {
		Object[] os = plus.keySet().toArray();
		String key;
		for (int i = 0; i < os.length; i++) {
			key = (String) os[i];
			if (target.containsKey(key)) {
				target.put(key, target.get(key) + plus.get(key));
			} else {
				target.put(key, plus.get(key));
			}
		}
		return target;
	}
public class Test
{
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("1", "value1");
        map.put("2", "value2");
        map.put("3", "value3");
        // 第一种 普遍使用,二次取值 通过Map.keySet遍历key和value
        for (String key : map.keySet()) {
            System.out.println("key= " + key + " and value= " + map.get(key));
        }
        // 第二种 通过Map.entrySet使用iterator遍历key和value:
        Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> entry = it.next();
            System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
        }
        // 第三种 推荐,尤其是容量大时 通过Map.entrySet遍历key和value
        for (Map.Entry<String, String> entry : map.entrySet()) {
            System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
        }
        // 第四种 通过Map.values()遍历所有的value,但不能遍历key
        for (String v : map.values()) {
            System.out.println("value= " + v);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_31451081/article/details/81201755