#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.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Stream;
@ -28,11 +29,11 @@ public abstract class AbstractDocument implements Document {
@Override
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)
.map(el -> (List<Map<String, Object>>) el)
.findAny().get().stream()
.map(constructor);
.findAny();
return any.isPresent() ? any.get().stream().map(constructor) : Stream.empty();
}
@Override

View File

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