用数字范围填充数组 [英] Fill arrays with ranges of numbers
本文介绍了用数字范围填充数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有任何语法/包允许使用数字范围快速填充 java 数组,例如在 perl 中?
Is there any syntax/package allowing quick filling of java arrays with ranges of numbers, like in perl?
例如
int[] arr = new int[1000];
arr=(1..500,301..400,1001..1400); // returns [1,2,3,4,...,500,301,302,...,400,1001,1002,...1400]
此外,这里有一个包,它允许获取上述数字列表中的第 n 个数字,而无需实际创建数组(可能很大)?
Also, it here a package that allows getting the n-th number in such list of numbers as the above, without actually creating the array (which can be huge)?
例如
BunchOfRangesType bort = new BunchOfRangesType("1..500","301..400","1001..1400");
bort.get(0); // return 1
bort.get(500); // return 301
bort.get(501); // return 302
实施起来并不难,但我想这可能很常见,所以可能已经完成了.
It's not too difficult to implement, but I guess it might be common so maybe it was already done.
推荐答案
不像 True Soft 的回答那么干净,但你可以使用 Google Guava 达到同样的效果:
Not quite as clean as True Soft's answer, but you can use Google Guava to the same effect:
public class Test {
public static void main(String[] args) {
//one liner
int[] array = toArray(newLinkedList(concat(range(1, 10), range(500, 1000))));
//more readable
Iterable<Integer> values = concat(range(1, 10), range(500, 1000));
List<Integer> list = newLinkedList(values);
int[] array = toArray(list);
}
public static List<Integer> range(int min, int max) {
List<Integer> list = newLinkedList();
for (int i = min; i <= max; i++) {
list.add(i);
}
return list;
}
}
请注意,您需要一些静态导入才能使其工作.
Note you need a few static imports for this to work.
这篇关于用数字范围填充数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文