Thursday, 12 September 2019

Stream to Optional

Was looking for a function that returns an Optional containing a value if it was the only value in the stream (size of stream is 1) and an empty Optional in every other case.

I came up with the following:

public class OneOptionalTest {
public static <T> Optional<T> getSingleton(Stream<T> stream)
{
return stream
.map(Optional::ofNullable)
.limit(2)
.reduce((a, b) -> Optional.empty())
.orElse(Optional.empty());
}
@Test
public void testOneOptional()
{
assertThat(getSingleton(Stream.of())).isEmpty();
assertThat(getSingleton(Stream.of("Maarten"))).contains("Maarten");
assertThat(getSingleton(Stream.of("Maarten", "Matthias"))).isEmpty();
assertThat(getSingleton(Stream.of("Maarten", "Matthias", "Peter"))).isEmpty();
assertThat(getSingleton(Stream.of("Maarten", "Matthias", "Peter", "Janine"))).isEmpty();
}
}

The limit that is put upon it, might make matters really performant, but perhaps not in the case of parallel streams.

See the javadoc of limit() on why this is.

No comments:

Post a Comment