欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 时评 > 《Java核心技术 卷II》流从迭代到流的操作

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

2025/2/21 2:59:13 来源:https://blog.csdn.net/qq_36324341/article/details/144835383  浏览:    关键词:《Java核心技术 卷II》流从迭代到流的操作

从迭代到流的操作

使用流时,看起来是:
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相对路径是指JavaCore2var 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待抄写

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词