Niks
Niks

Reputation: 35

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++)
{
    System.out.println(array[i]);
}

Upvotes: 2

Views: 550

Answers (3)

Rogue
Rogue

Reputation: 11483

How about:

IntStream.range(0, array.length / 2).map(i -> array[i]).forEach(System.out::println);

One line, and no array copies.

Broken down:

IntStream.range(0, array.length / 2)    //get the range of numbers 0 - (array length)/2
         .map(i -> array[i])            //map from index to value
         .forEach(System.out::println); //print result

Upvotes: 1

Amber Beriwal
Amber Beriwal

Reputation: 1598

The answer you have posted is good. Although, I couldn't find a better way to make it compact keeping the performance same, but performance can be improved. Remember following practices while coding:

  1. Algorithm's memory requirement should be optimum
  2. Algorithm's time i.e. performance should be optimum
  3. Algorithm's complexity should not be too much. For significant gains in 1 & 2, this can be skipped.
  4. Considering 1 & 2, lines of code comes at least priority.

Solution 1: This solution will be 4-5 times slower than your approach, plus Stream will take extra space.

Arrays.stream(array).limit(array.length/2).forEach(System.ou‌​t::println);

Solution 2: This solution is faster than the above code and your code (based on my testing), but Stream will take extra space. Also, it is not compact.

Arrays.stream(array).limit(array.length / 2).forEach(new IntConsumer() {
    @Override
    public void accept(int value) {
        System.out.println(value);
    }
});

Solution 3: As suggested by you.

int[] array = new int[] { 0, 1, 2, 3, 4, 5 };
int limit = array.length / 2;
for (int i = 0; i < limit; i++) {
    System.out.println(array[i]);
}

Recommendation: Don't go over to reduce the LOC at the stake of losing performance and memory. It is better to keep up with the solution that gives you best performance..

Upvotes: 0

Chris Gong
Chris Gong

Reputation: 8229

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,

Arrays.asList(array).forEach(System.out::println);

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);
Arrays.asList(newArray).forEach(System.out::println);

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,

Arrays.stream(array).limit(array.length/2).forEach(System.ou‌​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++)
{
    System.out.println(array[i]);
}

Upvotes: 4

Related Questions