How can I do this in short way without iterating just giving 5?
List<Integer> l = new ArrayList<Integer>();
for (int i = 1; i <= 5; i++) {
l.add(i);
}
l.addAll(Arrays.asList(1, 2, 3, 4, 5));
Or, you can initialize it with the specified values
List<Integer> l = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> l = Arrays.asList(1, 2, 3, 4, 5);
or with Java 8 streams:
List<Integer> l = IntStream.rangeClosed(1, 5).boxed().collect(Collectors.toList());
You need some upper bound for your loop. If you don't hard-code it as you did in the snippet, the value must come from somewhere.
You could use this constructor for the ArrayList data structure: public ArrayList(int initialCapacity) and bypass the loop altogether, but you won't have the initializers .
Take a look at Guava Ranges and this thread.
In short,
ContiguousSet.create(Range.closed(1, 500), DiscreteDomain.integers()).asList()
An easy way to do this is using Java 8 stream:
List<Integer> intList = IntStream.rangeClosed(1, 5).collect(Collectors.toList());