soupmagnet
soupmagnet

Reputation: 332

How can I iterate through elements of an array in Java?

In Bash, if I wanted to iterate through elements of an array in a given order, I could do so like this:

for i in 1 3 8 2 5 9; do
    array[i] = <some_algorithm_based_value>
done

Is it possible to do the same (or relatively the same) thing in Java?

Upvotes: 5

Views: 256

Answers (5)

M. Justin
M. Justin

Reputation: 21114

As this is a simple mapping from one set of values to the result of applying a function to each value, a stream-based approach would work:

int[] array = IntStream.of(1, 3, 8, 2, 5, 9).map(i -> algorithm(i)).toArray();

Upvotes: 0

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35557

You can try this

  int[] arr= new int[]{1, 3, 8, 2, 5, 9};
    for(int i:arr){
        System.out.println(i);
    }

Out put

1
3
8
2
5
9

Live demo here

FYI: This should work only in jdk 1.7, since early version of jdk can't have a primitive type for each.

So If you are using early version of java. you have to convert int[] to Integer[] You can try this

  int[] arr= new int[]{1, 3, 8, 2, 5, 9};
    Integer[] str=new Integer[arr.length];
    for(int i=0;i<arr.length;i++){
        str[i]=arr[i];
    }
    for(Integer i:arr){
        System.out.println(i);
    }

Out put

1
3
8
2
5
9

Upvotes: 3

Ray Toal
Ray Toal

Reputation: 88378

You can write

for (int i: Arrays.asList(1, 3, 8, 2, 5, 9)) {
    doSomethingWith(array[i]);
}

ADDENDUM: Live demo

Upvotes: 6

Daniel Kaplan
Daniel Kaplan

Reputation: 67320

You can do this:

package com.sandbox;

import java.util.Arrays;

public class Sandbox {

    public static void main(String[] args) {
        for (Integer integer : Arrays.asList(1, 2, 3, 4, 5)) {
            System.out.println(integer);
        }
    }


}

This will print out:

1
2
3
4
5

Upvotes: 1

Tony Ennis
Tony Ennis

Reputation: 12299

Yes, you can do it this way

    for (int i : new Integer[]{1, 3, 8, 2, 5, 9}) {
        // do something
    }

Upvotes: 1

Related Questions