Niks Niks - 10 days ago 4x
Java Question

Is there any way to shorten a for-each loop in java?

I want to iterate just the half of an array in java. Is there any elegant way to shorten this up, eg with a for-each loop?

int[] array = {0,1,2,3,4,5};

for (int i = 0; i<array.length/2; i++)


If you converted the array into a list using the asList method of the Arrays class in Java, then you can use the forEach method in the List class in Java to print out each element of the list in one single line,


To print only half the array, I'd suggest copying half the array into a new array using the copyOfRange method,

Integer[] newArray = Arrays.copyOfRange(array, 0, array.length/2);

EDIT: Like Marko Topolnik pointed out, we're actually starting out with an array of primitive types instead of object types, so in order to use the asList method we're going to have to convert the array into an array of objects (from int to Integer using Integer[] integerArray = ArrayUtils.toObject(array);). However this just seems tedious/inefficient and OP asked for a shorter way so my suggestion would be to use Marko's method,‌​t::println);

EDIT 2: Like Amber Beriwal pointed out, it should be noted that although the one-line solution above looks pretty due to its conciseness, it is still very inefficient/slow compared to the OP's original method. Therefore, I would like to reiterate Amber's comments that the OP and others should just stick with the original for-loop.

for (int i = 0; i < array.length/2; i++)