I have a stream with 0..n values. I want to:
- return value from stream if stream
count()is1 - return
defaultValueif streamcount()is0or> 1
Code what I developed resolved this problem:
String result = Stream.of("someValue")
.map(Optional::of) // reduce desn't accept `null`
.reduce((a, b) -> Optional.empty()) // instead `null`
.flatMap(Function.identity()) // unpack `Optional`
.orElseGet(() -> "defaultValue"); // if returned our optional is empty,
// so we can return default value
System.out.println(result);
But this hack with wraping stream values into Optional isn't easy to understand (in my opinion).
Do you know any other solution, which bases on stream API? How to write this in easy to read way?