#355 handle case when there are no child elements for the given key

This commit is contained in:
qza 2016-06-02 07:32:48 +02:00
parent 43f90ead48
commit f3110de130
2 changed files with 11 additions and 4 deletions

View File

@ -3,6 +3,7 @@ package com.iluwatar.abstractdocument;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
import java.util.function.Function; import java.util.function.Function;
import java.util.stream.Stream; import java.util.stream.Stream;
@ -28,11 +29,11 @@ public abstract class AbstractDocument implements Document {
@Override @Override
public <T> Stream<T> children(String key, Function<Map<String, Object>, T> constructor) { public <T> Stream<T> children(String key, Function<Map<String, Object>, T> constructor) {
return Stream.of(get(key)) Optional<List<Map<String, Object>>> any = Stream.of(get(key))
.filter(el -> el != null) .filter(el -> el != null)
.map(el -> (List<Map<String, Object>>) el) .map(el -> (List<Map<String, Object>>) el)
.findAny().get().stream() .findAny();
.map(constructor); return any.isPresent() ? any.get().stream().map(constructor) : Stream.empty();
} }
@Override @Override

View File

@ -29,7 +29,6 @@ public class AbstractDocumentTest {
public void shouldPutAndGetValue() { public void shouldPutAndGetValue() {
document.put(KEY, VALUE); document.put(KEY, VALUE);
assertEquals(VALUE, document.get(KEY)); assertEquals(VALUE, document.get(KEY));
System.out.println(document);
} }
@Test @Test
@ -45,4 +44,11 @@ public class AbstractDocumentTest {
assertEquals(2, childrenStream.count()); assertEquals(2, childrenStream.count());
} }
@Test
public void shouldRetrieveEmptyStreamForNonExistinChildren() {
Stream<DocumentImplementation> children = document.children(KEY, DocumentImplementation::new);
assertNotNull(children);
assertEquals(0, children.count());
}
} }