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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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