refactor(#248): simplify TagService.buildTree() to single-pass LinkedHashMap approach
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -4,6 +4,7 @@ import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
@@ -208,39 +209,20 @@ public class TagService {
|
||||
}
|
||||
|
||||
private List<TagTreeNodeDTO> buildTree(List<Tag> tags, Map<UUID, Long> counts) {
|
||||
Map<UUID, List<TagTreeNodeDTO>> childrenByParent = new HashMap<>();
|
||||
|
||||
for (Tag tag : tags) {
|
||||
childrenByParent.putIfAbsent(tag.getId(), new ArrayList<>());
|
||||
if (tag.getParentId() != null) {
|
||||
childrenByParent.computeIfAbsent(tag.getParentId(), k -> new ArrayList<>());
|
||||
}
|
||||
}
|
||||
|
||||
Map<UUID, TagTreeNodeDTO> nodeById = new LinkedHashMap<>();
|
||||
for (Tag tag : tags) {
|
||||
int documentCount = counts.getOrDefault(tag.getId(), 0L).intValue();
|
||||
TagTreeNodeDTO node = new TagTreeNodeDTO(
|
||||
nodeById.put(tag.getId(), new TagTreeNodeDTO(
|
||||
tag.getId(), tag.getName(), tag.getColor(), documentCount,
|
||||
childrenByParent.getOrDefault(tag.getId(), new ArrayList<>()),
|
||||
tag.getParentId()
|
||||
);
|
||||
if (tag.getParentId() != null) {
|
||||
childrenByParent.get(tag.getParentId()).add(node);
|
||||
new ArrayList<>(), tag.getParentId()
|
||||
));
|
||||
}
|
||||
for (TagTreeNodeDTO node : nodeById.values()) {
|
||||
if (node.parentId() != null) {
|
||||
TagTreeNodeDTO parent = nodeById.get(node.parentId());
|
||||
if (parent != null) parent.children().add(node);
|
||||
}
|
||||
}
|
||||
|
||||
// Collect root nodes (tags without a parent)
|
||||
List<TagTreeNodeDTO> roots = new ArrayList<>();
|
||||
for (Tag tag : tags) {
|
||||
if (tag.getParentId() == null) {
|
||||
int documentCount = counts.getOrDefault(tag.getId(), 0L).intValue();
|
||||
roots.add(new TagTreeNodeDTO(
|
||||
tag.getId(), tag.getName(), tag.getColor(), documentCount,
|
||||
childrenByParent.getOrDefault(tag.getId(), new ArrayList<>()),
|
||||
null
|
||||
));
|
||||
}
|
||||
}
|
||||
return roots;
|
||||
return nodeById.values().stream().filter(n -> n.parentId() == null).toList();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user