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

}
相关推荐
架构师沉默38 分钟前
设计多租户 SaaS 系统,如何做到数据隔离 & 资源配额?
java·后端·架构
该用户已不存在1 小时前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
Java中文社群2 小时前
重要:Java25正式发布(长期支持版)!
java·后端·面试
每天进步一点_JL3 小时前
JVM 类加载:双亲委派机制
java·后端
站大爷IP3 小时前
Java调用Python的5种实用方案:从简单到进阶的全场景解析
python
用户298698530144 小时前
Java HTML 转 Word 完整指南
java·后端
渣哥4 小时前
原来公平锁和非公平锁差别这么大
java
渣哥4 小时前
99% 的人没搞懂:Semaphore 到底是干啥的?
java
J2K4 小时前
JDK都25了,你还没用过ZGC?那真得补补课了
java·jvm·后端
kfyty7254 小时前
不依赖第三方,不销毁重建,loveqq 框架如何原生实现动态线程池?
java·架构