2023-06-04 00:00:00 +08:00
|
|
|
package xyz.zhouxy.plusone.commons.util;
|
|
|
|
|
|
|
|
import java.util.Collection;
|
|
|
|
import java.util.List;
|
|
|
|
import java.util.Map;
|
|
|
|
import java.util.Optional;
|
|
|
|
import java.util.function.BiConsumer;
|
|
|
|
import java.util.function.Function;
|
|
|
|
import java.util.stream.Collectors;
|
|
|
|
|
2023-07-19 01:25:21 +08:00
|
|
|
public class TreeBuilder<T, TSubTree extends T, TIdentity> {
|
2023-06-04 00:00:00 +08:00
|
|
|
private final Function<T, TIdentity> identityGetter;
|
|
|
|
private final Function<T, Optional<TIdentity>> parentIdentityGetter;
|
2024-03-02 14:48:19 +08:00
|
|
|
private final BiConsumer<TSubTree, T> addChildMethod;
|
2023-06-04 00:00:00 +08:00
|
|
|
|
2024-03-02 14:48:19 +08:00
|
|
|
public TreeBuilder(Function<T, TIdentity> identityGetter, Function<T, Optional<TIdentity>> parentIdentityGetter,
|
|
|
|
BiConsumer<TSubTree, T> addChild) {
|
2023-06-04 00:00:00 +08:00
|
|
|
this.identityGetter = identityGetter;
|
|
|
|
this.parentIdentityGetter = parentIdentityGetter;
|
2024-03-02 14:48:19 +08:00
|
|
|
this.addChildMethod = addChild;
|
2023-06-04 00:00:00 +08:00
|
|
|
}
|
|
|
|
|
2024-03-02 14:48:19 +08:00
|
|
|
public List<T> buildTree(Collection<T> nodes) {
|
2024-03-02 23:25:23 +08:00
|
|
|
Map<TIdentity, T> identityNodeMap = nodes.stream()
|
|
|
|
.collect(Collectors.toMap(identityGetter, Function.identity(), (n1, n2) -> n1));
|
2024-03-02 14:48:19 +08:00
|
|
|
List<T> result = nodes.stream()
|
2023-06-04 00:00:00 +08:00
|
|
|
.filter(node -> !this.parentIdentityGetter.apply(node).isPresent())
|
|
|
|
.collect(Collectors.toList());
|
2024-03-02 14:48:19 +08:00
|
|
|
nodes.forEach(node -> parentIdentityGetter.apply(node).ifPresent(parentIdentity -> {
|
|
|
|
if (identityNodeMap.containsKey(parentIdentity)) {
|
|
|
|
@SuppressWarnings("unchecked")
|
|
|
|
TSubTree parentNode = (TSubTree) identityNodeMap.get(parentIdentity);
|
|
|
|
addChildMethod.accept(parentNode, node);
|
2023-06-04 00:00:00 +08:00
|
|
|
}
|
2024-03-02 14:48:19 +08:00
|
|
|
}));
|
2023-06-04 00:00:00 +08:00
|
|
|
return result;
|
|
|
|
}
|
|
|
|
}
|