Skip to content

Commit b7270e6

Browse files
committed
fix:[uno-core] data-structure tree sentinel element
1 parent 2a6488a commit b7270e6

File tree

3 files changed

+29
-10
lines changed

3 files changed

+29
-10
lines changed

uno-core/src/main/java/cc/allio/uno/core/datastructure/tree/ComparableElement.java

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,13 @@
33
import java.io.Serializable;
44
import java.util.Comparator;
55

6+
/**
7+
* comparable tree element base on {@link Comparator}
8+
*
9+
* @author j.x
10+
* @date 2023/4/11 22:21
11+
* @since 1.1.4
12+
*/
613
public class ComparableElement<T extends ComparableElement<T>> extends DefaultElement<T> {
714

815
private final Comparator<T> comparator;
@@ -16,7 +23,12 @@ public ComparableElement(Serializable id, Comparator<T> comparator) {
1623
public void addChildren(T element) {
1724
super.addChildren(element);
1825
if (comparator != null) {
19-
getChildren().sort((o1, o2) -> comparator.compare((T) o1, (T) o2));
26+
getChildren().sort(comparator);
2027
}
2128
}
29+
30+
@Override
31+
public Element obtainSentinel() {
32+
return new ComparableElement(-1, comparator);
33+
}
2234
}

uno-core/src/main/java/cc/allio/uno/core/datastructure/tree/Element.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,7 @@ default void accept(Visitor<T> visitor) {
157157
/**
158158
* 获取Sentinel结点
159159
*/
160-
static Element getRootSentinel() {
160+
default Element obtainSentinel() {
161161
return new DefaultElement<>(-1, -1);
162162
}
163163
}

uno-core/src/main/java/cc/allio/uno/core/datastructure/tree/TreeSupport.java

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -88,15 +88,22 @@ public static <R extends Element<R>> List<R> adjust(List<R> elements) {
8888
}
8989
}
9090

91-
Element sentinel = Element.getRootSentinel();
92-
for (R virtual : idElement.values()) {
93-
if (virtual.getDepth() == Element.ROOT_NODE) {
94-
// 触发Element添加结点的特性,如排序
95-
sentinel.addChildren(virtual);
96-
}
97-
}
91+
// base on first element (if empty then return empty list) get sentinel element then traversal each element and add children (maybe trigger element feature, like as sort)
92+
return idElement.values()
93+
.stream()
94+
.findFirst()
95+
.map(Element::obtainSentinel)
96+
.map(sentinel -> {
97+
for (R virtual : idElement.values()) {
98+
if (virtual.getDepth() == Element.ROOT_NODE) {
99+
// 触发Element添加结点的特性,如排序
100+
sentinel.addChildren(virtual);
101+
}
102+
}
103+
return sentinel.getChildren();
104+
})
105+
.orElse(Collections.emptyList());
98106

99-
return sentinel.getChildren();
100107
}
101108

102109
/**

0 commit comments

Comments
 (0)