002.Stream流的创建方式(基于数组和集合最常用)

package com.imooc.stream;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * Stream流的创建方式
 */
public class StreamGenerator
{
    //1.基于数组创建
    @Test
    public void generator1()
    {
        String[] array = {"Lily", "Andy", "Jackson", "Smith"};
        Stream<String> stream = Stream.of(array);
        stream.forEach(s -> System.out.println(s));
    }

    //2.基于集合
    @Test
    public void generator2()
    {
        List<String> list = new ArrayList<>();
        list.add("Lily");
        list.add("Andy");
        list.add("Jackson");
        list.add("Smith");
        Stream<String> stream = list.stream();
        stream.forEach(s -> System.out.println(s));
    }

    //3.利用generate创建无线长度流
    @Test
    public void generator3()
    {
        Stream<Integer> stream = Stream.generate(() -> new Random().nextInt(10000));
        stream.limit(5).forEach(i -> System.out.println(i));//limit的作用时限制创建流的最大长度
    }

    //4.基于迭代器创建流
    @Test
    public void generator4()
    {
        Stream<Integer> stream = Stream.iterate(1, n -> n + 1);
        stream.limit(6).forEach(i -> System.out.println(i));
    }

    //5.基于字符创建流
    @Test
    public void generator5()
    {
        String str = "Aasdfghjkl";
        IntStream stream = str.chars();
        stream.forEach(c -> System.out.println((char) c));
        //   stream.forEach(c -> System.out.println(c));

    }
}

 

posted @ 2023-01-07 12:44  李林林  阅读(42)  评论(0编辑  收藏  举报