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.List;
import java.util.Map;

public class Main {
    public static <K, V extends Comparable<? super V>> Map<K, Integer> calculateCount(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++;
            result.put(key, value);
        }

        return result;
    }

    public static <K, V extends Comparable<? super V>> Map<K, Integer> calculateCount(List<K> list) {
        Map<K, Integer> result = new HashMap<K, Integer>();
        for (K key : list) {
            Integer value = (Integer) getValue(result, key, Integer.class);
            value++;
            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;
    }
}