流的使用

无状态:处理单个数据
有状态:处理所有数据
中间操作(无状态)中间操作(有状态)终端操作(短路)终端操作(非短路)
过滤(filter)去重(distinct)所有匹配(allMatch)遍历(forEach)
映射(map)跳过(skip)任意匹配(anyMatch)归约(reduce)
扁平化(flatMap)截断(limit)不匹配(noneMatch)最大值(max)
遍历(peek)排序(sorted)查找首个(findFirst)最小值(min)
查找任意(findAny)聚合(collect)
计数(count)

流的构建

通过值创建流
Stream stream = Stream.of(1,2,3,4);
通过数组创建流
int[] numbers = {1,2,3,4,5};
IntStream stream = Arrays.stream(numbers);
通过文件创建流
/**
         * 通过文件创建流
         * java nio
         */
        Stream<String> stream =
                Files.lines(Paths.get("D:\\guonan\\project\\myroom\\lambda_expression\\lambda_demo1\\src\\main\\java\\lambda_expression\\stream\\DistinctStreamTest.java"));
        stream.forEach(System.out::println);
通过函数生成流(无限流)
/**
         * 通过函数生成流
         */
        // 生成偶数流
        Stream stream1 = Stream.iterate(0, n -> n+2);
        stream1.limit(10).forEach(x -> System.out.print(x+" ")); // 0 2 4 6 8 10 12 14 16 18

        System.out.println();
        
        // 生成随机数流
        Stream stream2 = Stream.generate(Math::random);
        stream2.limit(10).forEach(x -> System.out.print(x+","));

阿南
20 声望7 粉丝

引用和评论

0 条评论