Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
343 views
in Technique[技术] by (71.8m points)

java - Fill arrays with ranges of numbers

Is there any syntax/package allowing quick filling of java arrays with ranges of numbers, like in perl?

e.g.

int[] arr = new int[1000];
arr=(1..500,301..400,1001..1400); // returns [1,2,3,4,...,500,301,302,...,400,1001,1002,...1400]

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)?

e.g.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For those still looking for a solution:

In Java 8 or later, this can be answered trivially using Streams without any loops or additional libraries.

int[] range = IntStream.rangeClosed(1, 10).toArray();

This will produce an array with the integers from 1 to 10.

A more general solution that produces the same result is below. This can be made to produce any sequence by modifying the unary operator.

int[] range = IntStream.iterate(1, n -> n + 1).limit(10).toArray();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...