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

}
相关推荐
李庆政370几秒前
Reactor-core 响应式编程 spring-boot-starter-webflux
java·spring boot·reactor·响应式编程·reactor-core
是Smoky呢2 分钟前
springAI+向量数据库+RAG入门案例
java·开发语言·ai编程
硅基喵10 分钟前
Python 入门:从“其他语言”到 Pythonic 思维的完整迁移手册
python
huabiangaozhi12 分钟前
修改表字段属性,SQL总结
java·数据库·sql
请为小H留灯14 分钟前
一键解决 IDEA 中 Java 项目变橙色的问题!!!
java·ide·maven·intellij-idea·java项目
liu****26 分钟前
LangChain-AI应用开发框架(二)
人工智能·python·langchain·大模型部署
小文大数据33 分钟前
python实现HTML转PDF
java·前端·数据库
_Twink1e33 分钟前
[算法竞赛]九、C++标准模板库STL常用容器大全
开发语言·c++
架构师沉默38 分钟前
为什么 Dubbo 从 ZooKeeper 转向 Nacos?
java·后端·架构
未来转换41 分钟前
OpenClaw 命令大全以及使用指南
python·ai·openclaw