简体   繁体   中英

Java: How do you accept an integer array without using a for loop?

Is it possible to accept an integer array from user without using a for loop? input will be :

4 //size

1 2 3 4 //array values

    String stdin="1 2 3 4";     
    String str[]= stdin.split(" ");
    int st[] = Integer.parseInt(stdin.split(" "));

this code does not work though

You can do this without a loop in Java 8 using stream.

Here is what you're looking for:

String str = "1 2 3 4";
int[] arr = Arrays.stream(str.split("\\s+"))
            .map(String::trim).mapToInt(Integer::parseInt).toArray();

Goodluck, thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM