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.Function;

public class Main {
    static <T, K> Map<K, List<T>> groupBy(List<T> elements, Function<T, K> classifier) {
        //TODO Implement me
        Map<K, List<T>> map = new HashMap<>();
        List<T> list = new ArrayList<>();
        for (T element : elements) {
            K value = classifier.apply(element);
            if (map.containsKey(value)) {
                map.get(value).add(element);
            } else {
                list.add(element);
                map.put(value, list);
            }
        }
        return map;
    }
}