3

I have arrays like this that are within a range:

int[] arr1 = {1,2,3,4,5,6};
int[] arr2 = {7,8,9,10,11};
int[] arr3 = {12,13,14,15,16,17,18,19};

Is there a one-line way to create these lists (possibly using a range function) similar to Python like this:

arr = list(range(1, 7))
karamazovbros
  • 950
  • 1
  • 11
  • 40

1 Answers1

4

Use IntStream.range:

int[] result = IntStream.range(startInclusive, endExclusive).toArray();

or IntStream.rangeClosed:

int[] result = IntStream.rangeClosed(startInclusive, endInclusive).toArray();
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
  • Is there a way without using IntStream,or importing? just wondering. – karamazovbros Jul 27 '18 at 22:29
  • @karamazovbros if you want to shorten it then you need to add the import `import static java.util.stream.IntStream.*;` which you can then do `int[] ints = range(startInclusive, endInclusive).toArray();` – Ousmane D. Jul 27 '18 at 22:31
  • That's good to know as well, but what I meant as not importing IntStream at all, like an alternative way without importing. – karamazovbros Jul 27 '18 at 22:32
  • you have to import a package in order to use things that are contained in it... this is not necessarily specific to `IntStream` even for lists you need to import for example `import java.util.List;` in order to use it. @karamazovbros – Ousmane D. Jul 27 '18 at 22:34
  • Yes, I know this. I guess I was wondering if there was something like list comprehension in Python that's just built-in without importing anything else. – karamazovbros Jul 27 '18 at 22:35
  • @Aomine you don't have to import it: `int[] result = java.util.stream.IntStream.range(startInclusive, endExclusive).toArray();` would work. – Andy Turner Jul 27 '18 at 22:50
  • @AndyTurner yes, you're right I guess. I can't remember when I _had to_ use that approach as importing just makes things a lot easier and more readable. – Ousmane D. Jul 27 '18 at 22:56