zoukankan      html  css  js  c++  java
  • Java之Stream笔记

    Stream流的创建方法

        public static void main(String[] args) {
    
            Stream stream1 = Stream.of("hello","world","hello stream");
    
            String[] myArray = new String[]{"hello","world","hello stream"};
            Stream stream2 = Arrays.stream(myArray);
            Stream stream3 = Stream.of(myArray);
    
            List<String> list = Arrays.asList(myArray);
            Stream stream4 = list.stream();
    
    
            stream1.forEach(System.out::println);
    
            stream2.forEach(System.out::println);
    
            stream3.forEach(System.out::println);
            
            stream4.forEach(System.out::println);
    
        }

    Stream的基础使用:

        public static void main(String[] args) {
            IntStream.range(1,10).forEach(System.out::println);
    
            //我来算一算 1+...+100 等于多少
            IntStream.rangeClosed(1,100).reduce(Integer::sum).ifPresent(System.out::print);
        }

    函数式编程传递的是一种行为,根据传递的行为处理数据

        public static void main(String[] args) {
    
            Stream<java.lang.String> stream = Stream.of("hello","world","hello stream");
    
            String[]  list =  stream.toArray(length -> new String[length]);
    
            for (int i = 0 ;i<list.length;i++){
                System.out.println(list[i]);
            }
        }
    <A> A[] toArray(IntFunction<A[]> generator);方法接收一个IntFunction<A[]>类型函数式接口,在IntFunction<A[]>中接收一个int 返回一个R 也就是返回A[],文档中有说明,【The generator function takes an integer, which is the size of the desired array 】这个int值就是这个流中array的size。

    所以这个lambada表达式是:

    String[] list = stream.toArray(length -> new String[length]);

    看到new Stirng[length],我们明显可以使用构造方法引用:

    String[] list2 = stream.toArray(String[]::new);
        public static void main(String[] args) {
    
            Stream<java.lang.String> stream = Stream.of("hello","world","hello stream");
    
    //        String[]  list =  stream.toArray(length -> new String[length]);
    //        for (int i = 0 ;i<list.length;i++){
    //            System.out.println(list[i]);
    //        }
    
            //等价于:
            String[] list2 = stream.toArray(String[]::new);
            for (int i = 0 ;i < list2.length;i++){
                System.out.println(list2[i]);
            }
        }
  • 相关阅读:
    正则表达式周二挑战赛 第七周
    [译]视区百分比,canvas.toBlob()以及WebRTC
    [译]因扩展Object.prototype而引发Object.defineProperty不可用的一个问题
    [译]JavaScript需要类吗?
    [译]JavaScript中几种愚蠢的写法
    [译]JavaScript中对象的属性
    JavaScript:数组的length属性
    [译]JavaScript中的变量声明:你可以打破的三条规则
    [译]ES6:JavaScript中将会有的几个新东西
    [译]ECMAScript 6中的集合类型,第三部分:WeakMap
  • 原文地址:https://www.cnblogs.com/zhvip/p/12838108.html
Copyright © 2011-2022 走看看