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

}
相关推荐
郝学胜-神的一滴1 分钟前
Qt 高级编程 037:QSS按钮样式封神指南
开发语言·c++·qt·软件工程·用户界面
DFT计算杂谈2 分钟前
SCIENTIFIC REPORTS 非 van der Waals可调二维磁性材料设计平台
开发语言·php
库拉库拉里11 分钟前
深入理解 C# 异步编程:同步、Task.Wait () 与 await 的本质区别及实践指南
开发语言·c#
霍霍的袁21 分钟前
【C++】string类 从 入门使用 到 底层深浅拷贝模拟实现
开发语言·c++·visual studio
酷在前行28 分钟前
【R绘图】Nature Communications 半眼图复刻:分布、区间与多面板排版(保姆级教程)
android·开发语言·r语言
2501_9378609433 分钟前
Java 集合底层深度剖析:Map 与 Set、二叉搜索树、哈希表全解
java·数据结构·散列表
这个人懒得名字都没写35 分钟前
Flask + PyArmor Gunicorn启动报错:RuntimeError: unauthorised use of script
python·flask·gunicorn·pyarmor
C++、Java和Python的菜鸟40 分钟前
第10章 后端Web进阶(Maven高级)
开发语言·python
cyforkk1 小时前
并发控制与状态安全:Single-Flight 与幂等性的本质区别
java·安全·spring
暗黑小白1 小时前
路由策略与引擎可替换性
后端·python·ai agent