《Java核心技术 卷II》流从迭代到流的操作

发布于:2025-02-11 ⋅ 阅读:(69) ⋅ 点赞:(0)

从迭代到流的操作

使用流时,看起来是:
long count = words.stream().filter(w -> w.length() > 12).count();
并行方式:将stream()替换为paralleStream()

流与集合差异:

  • 流不存储元素,元素存储在底层集合中。
  • 流不修改数据源。
  • 流操作是惰性执行,需要结果时才执行,理论可操作无限流。
工作流是操作流的典型,包含三个阶段:
  • 创建流。
  • 将初始流转换为其他中间操作的流,可包含多个步骤。
  • 应用终止操作,此操作强制执行惰性操作,之后这个流再也不能用了。

工作流案例

package streams;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

public class CountLongWords {

    public static void main(String[] args) throws IOException {
        //Path相对路径是指JavaCore2
        var contents = Files.readString(Path.of("./resources/alice.txt"));
        List<String> words = List.of(contents.split("\\PL+"));
        //通常用法统计
        long s1 = System.currentTimeMillis();
        long count = 0;
        for (String w : words) {
            if (w.length()>12) {
                count++;
            }
        }
        long e1 = System.currentTimeMillis();
        System.out.println(count+",用时:"+String.valueOf(e1-s1));
        //用流进行统计
        long s2 = System.currentTimeMillis();
        count = words.stream().filter(w -> w.length() > 12).count();
        long e2 = System.currentTimeMillis();
        System.out.println(count+",用时:"+String.valueOf(e2-s2));
        //用并发流进行统计
        long s3 = System.currentTimeMillis();
        count = words.parallelStream().filter(w -> w.length() > 12).count();
        long e3 = System.currentTimeMillis();
        System.out.println(count+",用时:"+String.valueOf(e3-s3));
    }

}

结果:并发居然用时更多,思考一下为什么?

API待抄写

网站公告

今日签到

点亮在社区的每一天
去签到