Java tutorial
//package com.java2s; /** * Copyright 2013-present febit.org (support@febit.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.*; import java.util.function.Function; public class Main { public static <T, K> TreeMap<K, List<T>> groupToTreeMap(Collection<T> collection, Function<T, K> keyFunc) { return groupToTreeMap(collection, keyFunc, (T arg1) -> arg1); } public static <T, K, V> TreeMap<K, List<V>> groupToTreeMap(Collection<T> collection, Function<T, K> keyFunc, Function<T, V> valueFunc) { TreeMap<K, List<V>> map = new TreeMap<>(); groupToMap(map, collection, keyFunc, valueFunc); return map; } public static <T, K> Map<K, List<T>> groupToMap(Collection<T> collection, Function<T, K> keyFunc) { return groupToMap(collection, keyFunc, (T arg1) -> arg1); } public static <T, K, V> Map<K, List<V>> groupToMap(Collection<T> collection, Function<T, K> keyFunc, Function<T, V> valueFunc) { Map<K, List<V>> map = new HashMap<>(); groupToMap(map, collection, keyFunc, valueFunc); return map; } protected static <T, K, V> void groupToMap(Map<K, List<V>> map, Collection<T> collection, Function<T, K> keyFunc, Function<T, V> valueFunc) { for (T t : collection) { K key = keyFunc.apply(t); List<V> list = map.computeIfAbsent(key, k -> new ArrayList<>()); list.add(valueFunc.apply(t)); } } }