3

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);
};

6 Answers 6

3

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]);
}
Sign up to request clarification or add additional context in comments.

3 Comments

I wrote the same answer. Sorry I didn't know you already posted it. Maybe I was writing that time.
@Clutchy You're welcome (and it seems like you just got enough rep to vote :))
I was learning Python before and everything seems so long for me in Java :P
2

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.

Comments

2

With Java 8, it can be done like this:

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

Comments

2

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();

Comments

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

1 Comment

Is this the only way?
1

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]);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.