2015-09-13 45 views
0

我有一個與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

我寫我自己的實用方法:

/** 
* 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; 
} 

我希望番石榴已經提供了這種方法還是有些另類。