Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.util.HashMap;

import java.util.Map;

public class Main {
    public static <K, V extends Comparable<? super V>> Map<K, Integer> calculateSum(Map<K, Integer> map) {
        Map<K, Integer> result = new HashMap<K, Integer>();
        for (Map.Entry<K, Integer> entry : map.entrySet()) {
            K key = entry.getKey();
            Integer value = (Integer) getValue(result, key, Integer.class);
            value += entry.getValue();
            result.put(key, value);
        }

        return result;
    }

    public static Number getValue(Map<? extends Object, ? extends Number> map, Object key, Class<?> clazz) {
        Number value = map.get(key);
        if (value == null) {
            if (clazz.equals(Double.class)) {
                value = 0.0;
            } else {
                value = 0;
            }
        }
        return value;
    }
}