7

Here, someone made a one-liner for loop in Python.

Another example is this:

someList = [f(i) for i in range(16)]

which would be a one-liner for this code:

someList = []
for i in range(16):
    someList.append(f(i))

or, in Java:

int[] someList = {}
for (int i = 0; i < 16; i++) {
    someList = append(someList, f(i));
}

such that f is some function that will return an integer.

Now, is there an equivalent one-liner in Java?

Note: Currently, I am using Processing, which is similar to Java, so, any code written in Java might be usable in Processing.

2
  • You can't append to an array in Java. Use an ArrayList or simply create array of correct size: int[] someList = new int[16] then do someList[i] = f(i) in the loop.
    – Andreas
    Commented Dec 3, 2016 at 10:51
  • 2
    Is there a reason you need this in one line? I'd argue that you should favor readability over shortness. The for loop solution is easy to understand. Why not just stick with that? Commented Dec 3, 2016 at 16:42

1 Answer 1

19

Java 8's IntStream to the rescue:

int[] someList = IntStream.range(0, 16).map(i -> f(i)).toArray();
1
  • 2
    @TimBiegeleisen The original list is the OP is empty, and seems to just be defined as a necessity. The original one-liner OP is trying to emulate creates a new list/array: someList = [f(i) for i in range(16)]
    – Mureinik
    Commented Dec 3, 2016 at 10:47

Not the answer you're looking for? Browse other questions tagged or ask your own question.