java8新特性学习——StreamAPI使用学习上(三)

public class StreamTest {

    /**
     *    StreamApi应用
     *    流就是为了能提高数据的处理效率,数据可以是集合、数组等
     *    注意:   stream 不会储存元素
     *            stream 不会改变对象
     *            stream  操作是延时的
     */

    /**
     *  创建流的步骤
     *  1. 创建流
     *  2. 操作流
     *  3. 终止流
     */

    /**
     * 创建流的方式
     */

    @Test
    public void  test (){
        // 1. 集合转换为stream流
        List<String> list = new ArrayList<>();
        Stream<String> stream = list.stream();
        // 2. 数组转换为stream流
        String[] strings = new String[5];
        Stream<String> stream1 = Arrays.stream(strings);
        // 3. 通过stream静态方法来获取
        Stream<String> stringStream = Stream.of("");
        // 4. 可以创建一种没有任何限制的流
        Stream<Integer> iterate = Stream.iterate(0, x -> x + 1);
    }

    /**
     * 流的使用案例
     * 1.过滤
     * 2.分页
     * 3.
     * 4.
     */
    public void test1(){

        List<Book> books = Arrays.asList(
                new Book("1", "1", "1", "1", 1, new Date()),
                new Book("2", "2", "2", "2", 2, new Date()),
                new Book("3", "3", "3", "3", 3, new Date()),
                new Book("4", "4", "4", "4", 4, new Date())
        );

        //过滤
        books.stream()
                .filter(x -> x.getAge() < 4)
                .forEach(System.out::println);


        //分页
        books.stream()
                .filter(x -> x.getAge() < 4)
                .limit(2)
                .skip(1)    //跳过
                .forEach(System.out::println);

        //使用集合转换为stream流
        List<String> list = Arrays.asList("1", "2", "3", "4");
        //数值大小/大小写
        list.stream()
                .map(x -> x+1)  //里可以做更多的操作
                .forEach(System.out::println);

        //类型的转变
        list.stream()
                .map(x -> x+"hellow")
                .forEach(System.out::println);

        //获取某个字段
        books.stream()
                .map(Book::getName)
                .forEach(System.out::println);

    }


    /**
     * 使用 flatMap接受一个函数作为参数使用,将流中的每个值都转为另一个流,然后再合并成一个流
     */
    @Test
    public void test2(){

        List<String> list = Arrays.asList("1", "2", "3", "4");

        list.stream()
                .flatMap(StreamTest::method)
                .forEach(System.out::println);

    }
    //必须调用一个静态方法
    public static Stream<String> method(String a){
        return  Stream.of(a);

    }
}

未完待续。。。。 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值