1

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);
    }
Lusi
  • 391
  • 9
  • 28

5 Answers5

7
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);
Predrag Maric
  • 23,938
  • 5
  • 52
  • 68
  • thank you for your answer, but 5 is dynamic it can be 4, 7 etc . – Lusi Feb 04 '15 at 12:47
  • @Lusi As Peter Lawrey said in the comment, even if you do find a utility method in some library that does this in one line, in the background it also uses iteration so you might as well write your own. – Predrag Maric Feb 04 '15 at 13:17
4
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());
v4ssili
  • 83
  • 5
0

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 .

nicomp
  • 4,344
  • 4
  • 27
  • 60
0

Take a look at Guava Ranges and this thread. In short, ContiguousSet.create(Range.closed(1, 500), DiscreteDomain.integers()).asList()

Community
  • 1
  • 1
Anna Zubenko
  • 1,645
  • 2
  • 11
  • 12
0

An easy way to do this is using Java 8 stream:

List<Integer> intList = IntStream.rangeClosed(1, 5).collect(Collectors.toList());
sprinter
  • 27,148
  • 6
  • 47
  • 78
  • 1
    you're missing the `boxed()` call which converts your `IntStream` to `Stream` so you actually can collect the values – v4ssili Feb 04 '15 at 13:42