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 {
    public static <T, K> Map<K, List<T>> groupBy(List<T> elements, Function<T, K> classifier) {
        Map<K, List<T>> result = new HashMap<>();
        for (T element : elements) {
            K key = classifier.apply(element);
            result.computeIfAbsent(key, e -> new ArrayList<>()).add(element);
        }

        return result;
    }
}