Fill arrays with ranges of numbers

前端 未结 6 607
甜味超标
甜味超标 2020-11-29 06:20

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,3         


        
6条回答
  •  情深已故
    2020-11-29 07:11

    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 values = concat(range(1, 10), range(500, 1000));
            List list = newLinkedList(values);
            int[] array = toArray(list);
    
        }
    
        public static List range(int min, int max) {
            List 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.

提交回复
热议问题