0

例如,是否可以在番石榴中创建偶数范围?就像是:

Range.closed(0,10) //0,2,4,6,8,10

我知道上面的行不会产生所需的输出,但可能是这样的:

Range.closed(0,10, SomeFunctionInterface<Integer>);

在哪里

 interface SomeFunctionInterface<T>{
      T computeNext(T first);
 }

番石榴可以吗?这仍然是一个连续的范围,只是对其应用了某个规则。

我只对番石榴解决方案感兴趣。

4

1 回答 1

6

Guava can support this if you compose two operations together. First, you create the set {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}. Then, you filter it.

To turn the Range into the intermediate, unfiltered set, create a ContiguousSet. To do so, you'll need a DiscreteDomain, which is basically the SomeFunctionInterface you've described. Since you're dealing with integers, you can use the built-in DiscreteDomain.integers().

To get from there to the set of only even numbers, you can write a Predicate and then pass it and the intermediate set to Sets.filter.

于 2013-04-22T14:16:30.080 回答