Java tutorial
//package com.java2s; //License from project: Open Source License import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; public class Main { public static <T, K> ArrayList<T> buildTree(Collection<T> list, Function<T, K> keyMapper, Function<T, K> parentKeyMapper, Function<T, Collection<T>> childMapper) { HashMap<K, T> map = toHashMap(list, keyMapper); ArrayList<T> root = new ArrayList<T>(); for (T t : list) { K key = keyMapper.apply(t); K parentKey = parentKeyMapper.apply(t); if (parentKey == null || key.equals(parentKey)) root.add(t); else childMapper.apply(map.get(parentKey)).add(t); } return root; } /** * Convert a collection to HashMap, The key is decided by keyMapper, value * is the object in collection * * @param entities * @param keyMapper * @return */ public static <T, K> HashMap<K, T> toHashMap(Collection<T> entities, Function<T, K> keyMapper) { return toMap(entities, keyMapper, HashMap<K, T>::new); } public static <T, K> HashMap<K, T> toHashMap(T[] entities, Function<T, K> keyMapper) { return toHashMap(Arrays.asList(entities), keyMapper); } public static <T, K, V> HashMap<K, V> toHashMap(Collection<T> entities, Function<T, K> keyMapper, Function<T, V> valueMapper) { return toMap(entities, keyMapper, valueMapper, HashMap<K, V>::new); } public static <T, K, V> HashMap<K, V> toHashMap(T[] entities, Function<T, K> keyMapper, Function<T, V> valueMapper) { return toHashMap(Arrays.asList(entities), keyMapper, valueMapper); } public static <T, K, M extends Map<K, T>> M toMap(Collection<T> entities, Function<T, K> keyMapper, Supplier<M> supplier) { return entities.stream().collect(Collectors.toMap(keyMapper, Function.identity(), (a, b) -> b, supplier)); } public static <T, K, V, M extends Map<K, V>> M toMap(Collection<T> entities, Function<T, K> keyMapper, Function<T, V> valueMapper, Supplier<M> supplier) { return entities.stream().collect(Collectors.toMap(keyMapper, valueMapper, (a, b) -> b, supplier)); } }