如何将一种类型的给定Guava Range转换为另一种类型的范围。
我期待一种类似于Predicates.compose的compose方法。以Integer和Long为例:
Range<Integer> intRange = Range.compose(Range.atLeast(10l),integerFromLongFunction);
我写了撰写方法:
public static <F extends Comparable<F>, T extends Comparable<T>> Range<T> compose(Range<F> range,
Function<F, T> function) {
Range<T> result;
if (range.hasUpperBound() && range.hasLowerBound()) {
T upperEndpoint = function.apply(range.upperEndpoint());
T lowerEndpoint = function.apply(range.lowerEndpoint());
result = Range.range(lowerEndpoint, range.lowerBoundType(), upperEndpoint, range.upperBoundType());
} else if (range.hasUpperBound()) {
result = Range.upTo(function.apply(range.upperEndpoint()), range.upperBoundType());
} else if (range.hasLowerBound()) {
result = Range.downTo(function.apply(range.lowerEndpoint()), range.lowerBoundType());
} else {
result = Range.all();
}
return result;
}
单元测试:
@Test
public void testLongRangeToInteger() {
Integer inRange = 6;
Integer outOfRange = 3;
Range<Long> longRange = Range.atLeast(5l);
assertTrue(longRange.apply(inRange.longValue()));
assertFalse(longRange.apply(outOfRange.longValue()));
Function<Long, Integer> function = integerFromLongFunction();
Range<Integer> intRange = RangeExtended.compose(longRange, function);
assertTrue(intRange.apply(inRange));
assertFalse(intRange.apply(outOfRange));
}
public static Function<Long, Integer> integerFromLongFunction() {
return new Function<Long, Integer>() {
@Override
public Integer apply(Long input) {
return (input == null) ? null : input.intValue();
}
};
}
我目前的愿望实际上是将Joda持续时间转换为相应的毫秒,但为了简单起见,我在Long / Integer中编写了示例。
似乎番石榴会有这个,但我找不到任何地方。我使用v14,但是查看最新的v17 javadoc并没有暴露任何内容。
答案 0 :(得分:0)
我认为这就是你要找的东西
public static final Function<Range<Duration>, Range<Long>> DURATION_RANGE_TO_LONG_RANGE = new Function<Range<Duration>, Range<Long>>() {
@Override
public Range<Long> apply(final Range<Duration> input) {
return Range.range(input.lowerEndpoint()
.getMillis(), input.lowerBoundType(), input.upperEndpoint()
.getMillis(), input.upperBoundType());
}
};
public static final void main(final String... args) {
final List<Range<Duration>> durationRanges = ImmutableList.of(
Range.closedOpen(Duration.millis(100), Duration.millis(200)),
Range.closedOpen(Duration.millis(200), Duration.millis(300)));
final List<Range<Long>> longRanges = FluentIterable.from(durationRanges)
.transform(DURATION_RANGE_TO_LONG_RANGE)
.toList();
//[[100‥200), [200‥300)]
System.out.println(longRanges);
}