《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);
    }

}
相关推荐
用户0332126663677 分钟前
Python 实用技巧:从零自主生成结构化 PDF 页面
python
benchmark_cc8 分钟前
前复权数据每天可能变化,历史数据库应该覆盖还是保留原始价格?
大数据·python·pandas·量化交易·股票数据·quantdash
计算机编程指导师22 分钟前
计算机毕设选题推荐:Hadoop大数据下的个体肥胖健康风险评估与可视化系统源码 毕业设计 毕设选题 数据分析 机器学习
大数据·hadoop·python·spark·毕业设计·课程设计·肥胖健康风险
code2cat25 分钟前
【随笔】MCP输入Schema:把参数错误拦在工具执行之前
python·json schema·ai agent·mcp
Peregrine926 分钟前
C++ - > 类和对象
java·c++·算法
余醉 | dtminer30 分钟前
56%的保护效应藏在乳腺密度里:Nat Commun 高分中介孟德尔随机化全 R 管线拆解(附核心图)
开发语言·r语言·孟德尔随机化
2501_9339232533 分钟前
SpringCloud组件:Eureka服务注册与发现
java·开发语言·后端·spring cloud·eureka
Wang's Blog34 分钟前
Java 中间件之 RabbitMQ 快速入门: SpringAMQP 消息转换器
java·中间件·java-rabbitmq
计算机编程指导师37 分钟前
Python大数据毕设怎么写?Django结合Hadoop+Spark京东销售分析系统源码 毕业设计 选题推荐 毕设选题 数据分析 机器学习
大数据·hadoop·python·spark·毕业设计·课程设计·京东商品
合尘猫43 分钟前
AI 项目上线就停:一次事件循环阻塞的完整排查过程
人工智能·后端·python