I have a stream of enum values that I want to reduce. If the stream is empty or contains different values, I want null
. If it only contains (multiple instances of) a single value, I want that value.
[] null
[A, B, A] null
[A] A
[A, A, A] A
I tried to do it with a reduce:
return <lots of filtering, mapping, and other stream stuff>
.reduce((enum1, enum2) -> enum1 == enum2 ? enum1 : null)
.orElse(null);
Unfortunately, this does not work, because this reduce method throws a NullPointerException
when the result is null
. Does anyone know why that happens? Why is null
not a valid result?
For now, I solved this like this:
MyEnum[] array = <lots of filtering, mapping, and other stream stuff>
.distinct()
.toArray(MyEnum[]::new);
return array.length == 1 ? array[0] : null;
While this works, I am not satisfied with this "detour". I liked the reduce because it seemed to be the right fit and put everything into one stream.
Can anyone think of an alternative to the reduce (that ideally is not too much code)?