Java tutorial
//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; } }