As the title says, it is a trick that can be used when you are given a group of numerical values separated by spaces in standard input and want to replace them with Integer at once. (As a side note, in the case of Java, if you use nextInt () of java.util.Scanner, you can receive the standard input directly as an Integer, so I think that it will be less thankful in the context of receiving from the standard input.)
Those who want to know how to make List
Conclusion: You can do it using the stream API
You can do this by using streamApi as shown below. As a miso, use map (Integer :: valueOf) to convert to Integer, and Collectors.toList () to make the final result a List.
Main.java
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) throws Exception {
String[] strArray = "1 2 3 4 5".split(" ");
for( Integer i : strArrayToIntList(strArray) ) {
System.out.println(i * i);
}
}
private static List<Integer> strArrayToIntList(String[] strArray) {
List<Integer> intList =
Arrays
.stream(strArray)
.map(Integer::valueOf)
.collect(Collectors.toList());;
return intList;
}
}
Recommended Posts