Skip to content

Commit 06ab653

Browse files
fix: simplify children() with safe casting and null handling
1 parent ede37bd commit 06ab653

File tree

1 file changed

+11
-9
lines changed

1 file changed

+11
-9
lines changed

abstract-document/src/main/java/com/iluwatar/abstractdocument/AbstractDocument.java

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@
2424
*/
2525
package com.iluwatar.abstractdocument;
2626

27-
import java.util.Collection;
2827
import java.util.List;
2928
import java.util.Map;
3029
import java.util.Objects;
@@ -52,16 +51,19 @@ public Object get(String key) {
5251
return documentProperties.get(key);
5352
}
5453

55-
@Override
56-
public <T> Stream<T> children(String key, Function<Map<String, Object>, T> childConstructor) {
57-
return Stream.ofNullable(get(key))
58-
.filter(Objects::nonNull)
59-
.map(el -> (List<Map<String, Object>>) el)
60-
.findAny()
61-
.stream()
62-
.flatMap(Collection::stream)
54+
@SuppressWarnings("unchecked")
55+
@Override
56+
public <T> Stream<T> children(String key, Function<Map<String, Object>, T> childConstructor) {
57+
Object value = get(key);
58+
if (value instanceof List<?>) {
59+
return ((List<?>) value).stream()
60+
.filter(e -> e instanceof Map) // Only keeping items that are actually maps before casting
61+
.map(e -> (Map<String, Object>) e)
6362
.map(childConstructor);
6463
}
64+
return Stream.empty();
65+
}
66+
6567

6668
@Override
6769
public String toString() {

0 commit comments

Comments
 (0)