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

}
相关推荐
We་ct1 分钟前
LeetCode 50. Pow(x, n):从暴力法到快速幂的优化之路
开发语言·前端·javascript·算法·leetcode·typescript·
阿里嘎多学长3 分钟前
2026-04-12 GitHub 热点项目精选
开发语言·程序员·github·代码托管
EnCi Zheng5 分钟前
P2G-Python字符串方法完全指南-split、join、strip、replace的Python编程利器
开发语言·python
潇洒畅想6 分钟前
1.1 从∑到∫:用循环理解求和与累积
java·数据结构·python·算法
爱学习的小囧7 分钟前
VCF 9 实验室网络部署全攻略:从硬件连接到配置实操
开发语言·网络·php
有一个好名字7 分钟前
Claude Code 50+命令全解析
python
liliangcsdn18 分钟前
LLM如何与mcp server交互示例
linux·开发语言·python
Lupino19 分钟前
拯救迷失的荧光溶解氧传感器:从“三无”到“复活”的全记录
python
军军君0124 分钟前
Three.js基础功能学习十五:智能黑板实现实例二
开发语言·前端·javascript·vue.js·3d·threejs·三维
维齐洛波奇特利(male)27 分钟前
@Pointcut(“execution(* com.hdzx..*(..))“)切入点与aop 导致无限循环
java·开发语言