Clutchy
Clutchy

Reputation: 252

Java - making an array using for loop

Is it possible in Java to make an array in a style similar to this, i have been searching for a while and haven't found anything.

int[] foo = {
    for(String arg:args)
        return Integer.parseInt(arg);
};

Upvotes: 3

Views: 101

Answers (6)

Vitalii Elenhaupt
Vitalii Elenhaupt

Reputation: 7326

With array no, but you can do something similar with List:

final String args[] = {"123", "456", "789"};

List<Integer> list = new LinkedList<Integer>(){
    {
        for (String arg: args){
            add(Integer.parseInt(arg));
        }
    }
};

System.out.println(list); // [123, 456, 789]

With array you have to do the following:

int[] foo = new int[args.length];
for (int i = 0; i < foo.length; i ++) {
    foo[i] = Integer.parseInt(args[i]);
}

Upvotes: 1

Pshemo
Pshemo

Reputation: 124215

Kind of... Since Java 8 we have streams which can simulate loop and allow us to do things like

int[] arr = Arrays.stream(args).mapToInt(s -> Integer.parseInt(s)).toArray();

or its equivalent using method references

int[] arr = Arrays.stream(args).mapToInt(Integer::parseInt).toArray();

Upvotes: 2

Rohit Jain
Rohit Jain

Reputation: 213223

With Java 8, it can be done like this:

int[] foo = Stream.of(args).mapToInt(str -> Integer.parseInt(str)).toArray();

Upvotes: 2

shauryachats
shauryachats

Reputation: 10385

Not exactly, but try this.

int[] foo = new int[args.length]; //Allocate the memory for foo first.
for (int i = 0; i < args.length; ++i)
    foo[i] = Integer.parseInt(args[i]);
//One by one parse each element of the array.

Upvotes: 2

Zielu
Zielu

Reputation: 8552

int[] foo = new int[arg.length];
for (int i =0;i<args.length;i++) foo[i]=Integer.parseInt(args[i]);

Upvotes: 1

Eran
Eran

Reputation: 393781

No, but you can do this instead :

int[] foo = new int[args.length];
for(int i = 0; i < foo.length; i++) {
    foo[i] = Integer.parseInt(args[i]);
}

Upvotes: 3

Related Questions