Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java one liner for loop

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.

like image 525
The Holy See Avatar asked Jun 09 '26 10:06

The Holy See


1 Answers

Java 8's IntStream to the rescue:

int[] someList = IntStream.range(0, 16).map(i -> f(i)).toArray();
like image 123
Mureinik Avatar answered Jun 11 '26 00:06

Mureinik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!