把一個包裝類型數組String[]、Integer[]等轉化成int[]等基本類型數組,是在太不想用for循環就用Java8的stream吧java
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); } }