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

}
相关推荐
python-码博士4 分钟前
关于sklearn中StandardScaler的使用方式
人工智能·python·sklearn
悟空码字7 分钟前
SpringBoot 整合 ElasticSearch,给搜索插上“光速翅膀”
java·后端·elasticsearch
江公望8 分钟前
PyWebview浅谈
python
ULTRA??9 分钟前
各种排序算法时间复杂度分析和实现和优势
c++·python·算法·排序算法
0思必得011 分钟前
[Web自动化] HTML5常见新增标签
前端·python·自动化·html5·web自动化
Alair‎11 分钟前
103React数据处理
开发语言·前端·javascript
博语小屋12 分钟前
简单线程池实现(单例模式)
linux·开发语言·c++·单例模式
闲人编程15 分钟前
JWT认证与OAuth2集成
python·认证·jwt·签名·头部·负载·codecapsule
骚戴17 分钟前
DeepSeek V3 & Llama 3 推理避坑指南:自建 vLLM 集群 vs API 网关架构深度对比
java·人工智能·python·大模型·api·vllm
墨雪不会编程22 分钟前
C++基础语法篇八 ——【类型转换、再探构造、友元】
java·开发语言·c++