我有Guava Range上限和下限:
Integer upper = 5;
Integer lower = 3;
Range<Integer> range = Range.closed(lower,upper);
我希望在给定范围内的值类似于Math.min和Math.max:
Integer above = 6;
Integer within = 4;
Integer below = 2;
assert range.apply(above) == upper;
assert range.apply(below) == lower;
assert range.apply(within) == within;
Range.apply实现了Predicate.apply,所以上面的代码没有编译,但我正在寻找一些实用程序中的等效方法,否则会给出给定的值,如果它在边界内或返回最近的绑定端点,如果没有。
答案 0 :(得分:0)
我编写了自己的实用程序方法:
/**
* Ensures the value given is with the range or returns the nearest boundary endpoint.
*
* WARNING: This only works with closed ranges.
* Open ranges will return an endpoint that will return false from Range.contains().
* @param range
* @param value
* @return
*/
@Nonnull
public static <C extends Comparable<C>> C apply(@Nonnull Range<C> range, @Nonnull C value) {
C result;
if (value == null || range.contains(value)) {
result = value;
} else if (range.hasLowerBound() && range.lowerEndpoint().compareTo(value) >= 0) {
result = range.lowerEndpoint();
} else if (range.hasUpperBound() && range.upperEndpoint().compareTo(value) <= 0) {
result = range.upperEndpoint();
} else {
throw new IllegalStateException("Range should contain or violate one of the bounds " + range + " for "
+ value);
}
return result;
}
我希望Guava已经提供了这种方法或其他替代方法。