填充阵列,数字范围 [英] Fill arrays with ranges of numbers

查看:130
本文介绍了填充阵列,数字范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有语法/包,它允许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.

推荐答案

不太一样干净真正的软的答案,但是你可以使用的谷歌番石榴以同样的效果:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆