Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;

import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class Main {
    public static Map<? extends Object, ? extends Double> merge(Map<? extends Object, ? extends Double> map1,
            Map<? extends Object, ? extends Double> map2) {
        Map<Object, Double> result = new HashMap<Object, Double>();

        Map<? extends Object, ? extends Double> biggerMap = map1.size() > map2.size() ? map1 : map2;
        Map<? extends Object, ? extends Double> smallerMap = map1.size() > map2.size() ? map2 : map1;

        for (Entry<? extends Object, ? extends Double> entry : smallerMap.entrySet()) {
            Object key = entry.getKey();
            Double value = entry.getValue();

            Double value2 = (Double) getValue(biggerMap, key, Double.class);
            value2 += value;
            result.put(key, value2);
            biggerMap.remove(key);
        }
        result.putAll(biggerMap);
        return sortByValueDesc(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;
    }

    public static <K, V extends Comparable<? super V>> Map<K, V> sortByValueDesc(Map<K, V> map) {
        return sortByValueDesc(map, -1);
    }

    public static <E, V extends Comparable<? super V>, K> Map<K, V> sortByValueDesc(Map<K, V> map, int limit) {
        List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
            public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
                return (o2.getValue()).compareTo(o1.getValue());
            }
        });

        Map<K, V> result = new LinkedHashMap<K, V>();
        int counter = 0;
        for (Map.Entry<K, V> entry : list) {
            if (limit > 0 && counter >= limit) {
                break;
            }
            result.put(entry.getKey(), entry.getValue());
            counter++;
        }
        return result;
    }
}