博客 / 詳情

返回

Java Stream流的使用

流的使用

無狀態:處理單個數據
有狀態:處理所有數據
中間操作(無狀態) 中間操作(有狀態) 終端操作(短路) 終端操作(非短路)
過濾(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+","));
user avatar zzd41 頭像 software_arch 頭像 qiupingan 頭像
3 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.