Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.util.*;
import java.util.function.BinaryOperator;

import java.util.function.Function;

public class Main {
    static <T, K, U> Map<K, U> toMap(List<T> elements, Function<T, K> keyFunction, Function<T, U> valueFunction,
            BinaryOperator<U> mergeFunction) {
        //TODO Implement me
        Map<K, U> map = new HashMap<>();
        K key;
        U value;
        for (T element : elements) {
            key = keyFunction.apply(element);
            value = valueFunction.apply(element);
            if (map.containsKey(key)) {
                map.put(key, mergeFunction.apply(map.get(key), value));
            } else {
                map.put(key, value);
            }
        }
        return map;
    }
}