I am trying to calculate the minimum between some values using lambdas. These values may contain nulls which is normal for my business case, as they represent interval limits. For example if I have the next intervals (null, 10], (10, 15], [20, null)
- I want to check which is the lowest interval boundary between values (null, 10, 20)
and I expect null
to be the result (as null should be considered the equivalent of –infinity as a business case rule).
I tried implementing this with streams but I noticed that the min method from the Stream class cannot be used for such a scenario.
private Integer lowestIntervalLimit(Integer... intervalsLowerLimits) {
return Arrays.stream(intervalsStart)
.min(nullsFirst(Integer::compareTo))
.orElse(null);
}
The reason is described in the min method Javadoc “Throws: NullPointerException - if the minimum element is null”. I tried a workaround and used reduce instead of min but I have the exact same issue:
private Integer lowestIntervalLimit(Integer... intervalsLowerLimits) {
return Arrays.stream(intervalsStart)
.reduce(BinaryOperator.minBy(nullsFirst(Integer::compareTo)))
.orElse(null);
}
Am I missing something here or is this an API limitation and I should stick to fors and ifs?