Java代码如何将数组转换为流呢?
下文笔者讲述将数组转换为流的方法分享,如下所示
数组转流的实现思路
实现思路: 使用Arrays.stream或Stream.of 即可将Array转换为Stream例:
package com.java265.java8; import java.util.Arrays; import java.util.stream.Stream; public class TestJava8 { public static void main(String[] args) { String[] array = {"a", "b", "c", "d", "e"}; //Arrays.stream Stream<String> stream1 = Arrays.stream(array); stream1.forEach(x -> System.out.println(x)); //Stream.of Stream<String> stream2 = Stream.of(array); stream2.forEach(x -> System.out.println(x)); } }
原始数组转Stream
package com.java265.java8; import java.util.Arrays; import java.util.stream.IntStream; import java.util.stream.Stream; public class TestJava8 { public static void main(String[] args) { int[] intArray = {88,99,100,110,220,330}; // 1. Arrays.stream -> IntStream IntStream intStream1 = Arrays.stream(intArray); intStream1.forEach(x -> System.out.println(x)); // 2. Stream.of -> Stream<int[]> Stream<int[]> temp = Stream.of(intArray); // Cant print Stream<int[]> directly, convert / flat it to IntStream IntStream intStream2 = temp.flatMapToInt(x -> Arrays.stream(x)); intStream2.forEach(x -> System.out.println(x)); } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。