《Java核心技术II》简单约简

简单约简

约简(reduction)是一种终结操作,将流约简为非流值。

看过一种简单的约简:count方法返回流中元素的数量。

还有max和min,返回最大值和最小值。

这些方法返回的都是Optional的值,英文意思:可选的,代码中指的是这个T可能为空,也可能不为空。

Optional提供了一种更加优雅和安全的方式来处理可能为null的值。

获得流中的最大值:

Optional largest = words.max(String::compareToIgnoreCase);

System.out.println("largest:"+largest.orElse(""));

获得非空集合的第一个值

Optional startsWithQ = words.filter(s->s.startsWith("Q")).findFirst();

只想知道是否存在匹配

boolean aWordStartsWithQ = words.prarllel().anyMatch(s->s.startsWith("Q"));

包括allMatch和noneMatch方法。

约简整体案例
java 复制代码
package streams;

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

public class Reduction {

    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+"));
        //max
        Optional<String> largest = words.stream().max(String::compareToIgnoreCase);
        System.out.println("largest: "+largest.orElse(""));
        //findFirst
        Optional<String> startsWithQ = words.stream().filter(s->s.startsWith("Q")).findFirst();
        System.out.println("startsWithQ: "+startsWithQ.orElse(""));
        //findAny
        boolean aWordStartWithABC = words.parallelStream().anyMatch(s->s.startsWith("ABC"));
        System.out.println("aWordStartWithABC: "+aWordStartWithABC);
        //allMatch
        boolean aWordStartWithABCallMatch = words.parallelStream().allMatch(s->s.startsWith("ABC"));
        System.out.println("aWordStartWithABCallMatch: "+aWordStartWithABCallMatch);
        //noneMatch
        boolean aWordStartWithABCnoneMatch = words.parallelStream().noneMatch(s->s.startsWith("ABC"));
        System.out.println("aWordStartWithABCnoneMatch: "+aWordStartWithABCnoneMatch);
    }

}
相关推荐
lanboAI4 分钟前
基于卷积神经网络的舌苔诊断系统,resnet50,alexnet, shufflenet模型【pytorch框架+python源码】
pytorch·python·cnn
计算机安禾5 分钟前
【数据结构与算法】第10篇:项目实战:学生信息管理系统(线性表版)
开发语言·数据结构·算法·visual studio
QWsin13 分钟前
【Pydantic】Pydantic 是什么?
python
WeeJot嵌入式13 分钟前
爬虫对抗:ZLibrary反爬机制实战分析
爬虫·python·网络安全·playwright·反爬机制
MyBFuture14 分钟前
Halcon模板匹配核心技术解析大全
开发语言·人工智能·计算机视觉·halcon·机器视觉
毕设源码-朱学姐18 分钟前
【开题答辩全过程】以 基于SSM的宜佳家具电商平台为例,包含答辩的问题和答案
java
精神小伙就是猛20 分钟前
使用go-zero快速搭建一个微服务(一)
开发语言·后端·微服务·golang
不会聊天真君64722 分钟前
基础语法·下(golang笔记第三期)
开发语言·笔记·golang
客卿12327 分钟前
最小生成树(贪心)--构造回文串(字符串 + 回文判断 + 构造)
java·开发语言·算法
Bert.Cai27 分钟前
Python input函数作用
开发语言·python