把一個包裝類型數組String[]、Integer[]等轉化成int[]等基本類型數組,是在太不想用for循環就用Java8的stream吧
public class ToStreamIntString{
Scanner in = new Scanner(System.in);
List list = new ArrayList<>();
for (int i = 0; i < 3; i++) {
list.add(in.nextLine());
}
String n = list.get(0);
System.out.println("\n---> String\n"+n);
String[] xs = list.get(1).split("\\s+");
String[] ys = list.get(2).split("\\s+");
System.out.println("\n---> String[] to int[]"); // 需要輸入純數字
int[] x = Arrays.stream(xs).mapToInt(Integer::valueOf).toArray();
Arrays.stream(x).forEach( (i)-> System.out.print(i+10+" ") );
System.out.println("\n\n---> String[] to List, List to Stream");
List y = Arrays.asList(ys);
y.stream().forEach((i)-> System.out.print(i+" "));
}
測試結果:
Java8的Stream可以用多種方式獲取,其中對集合類來說就可以直接使用stream()方法,查看源碼可以知道Collection接口新增了default方法Stream<E> stream()。
public interface Collection<E> extends Iterable<E> {
/**
* @since 1.8
*/
default Stream<E> stream() {
return StreamSupport.stream(spliterator(), false);
}
}
