Skip to content

Commit f3110de

Browse files
committed
iluwatar#355 handle case when there are no child elements for the given key
1 parent 43f90ea commit f3110de

File tree

2 files changed

+11
-4
lines changed

2 files changed

+11
-4
lines changed

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

+4-3
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import java.util.List;
44
import java.util.Map;
55
import java.util.Objects;
6+
import java.util.Optional;
67
import java.util.function.Function;
78
import java.util.stream.Stream;
89

@@ -28,11 +29,11 @@ public Object get(String key) {
2829

2930
@Override
3031
public <T> Stream<T> children(String key, Function<Map<String, Object>, T> constructor) {
31-
return Stream.of(get(key))
32+
Optional<List<Map<String, Object>>> any = Stream.of(get(key))
3233
.filter(el -> el != null)
3334
.map(el -> (List<Map<String, Object>>) el)
34-
.findAny().get().stream()
35-
.map(constructor);
35+
.findAny();
36+
return any.isPresent() ? any.get().stream().map(constructor) : Stream.empty();
3637
}
3738

3839
@Override

abstract-document/src/test/java/com/iluwatar/abstractdocument/AbstractDocumentTest.java

+7-1
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,6 @@ private class DocumentImplementation extends AbstractDocument {
2929
public void shouldPutAndGetValue() {
3030
document.put(KEY, VALUE);
3131
assertEquals(VALUE, document.get(KEY));
32-
System.out.println(document);
3332
}
3433

3534
@Test
@@ -45,4 +44,11 @@ public void shouldRetrieveChildren() {
4544
assertEquals(2, childrenStream.count());
4645
}
4746

47+
@Test
48+
public void shouldRetrieveEmptyStreamForNonExistinChildren() {
49+
Stream<DocumentImplementation> children = document.children(KEY, DocumentImplementation::new);
50+
assertNotNull(children);
51+
assertEquals(0, children.count());
52+
}
53+
4854
}

0 commit comments

Comments
 (0)