Java代码如何将数组转换为流呢?

乔欣 Java经验 发布时间:2023-02-03 16:15:42 阅读数:14072 1
下文笔者讲述将数组转换为流的方法分享,如下所示

数组转流的实现思路

实现思路:
    使用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));
 
    }
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202302/16754121905639.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者