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

}
相关推荐
liulilittle3 分钟前
深度剖析:OPENPPP2 libtcpip 实现原理与架构设计
开发语言·网络·c++·tcp/ip·智能路由器·tcp·通信
88号技师10 分钟前
2025年6月一区-田忌赛马优化算法Tianji’s horse racing optimization-附Matlab免费代码
开发语言·算法·matlab·优化算法
Tipriest_11 分钟前
Python关键字梳理
python·关键字·keyword
勤奋的知更鸟16 分钟前
Java 编程之模板方法模式
java·开发语言·模板方法模式
逸风尊者37 分钟前
开发易掌握的知识:GeoHash查找附近空闲车辆
java·后端
碎叶城李白1 小时前
若依学习笔记1-validated
java·笔记·学习·validated
上单带刀不带妹1 小时前
手写 Vue 中虚拟 DOM 到真实 DOM 的完整过程
开发语言·前端·javascript·vue.js·前端框架
im_AMBER2 小时前
学习日志05 python
python·学习
都叫我大帅哥2 小时前
🌊 Redis Stream深度探险:从秒杀系统到面试通关
java·redis
都叫我大帅哥2 小时前
Redis持久化全解析:从健忘症患者到记忆大师的逆袭
java·redis