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

}
相关推荐
深度红薯5 分钟前
SAM3:开放式分割,太强了(后面有SAM3权重下载方式)(单图测试、视频测试、实时跟踪)
图像处理·人工智能·python·深度学习·毕业设计·毕设·sam3
c++之路8 分钟前
C++ 面向对象编程(OOP)
开发语言·c++
weixin_424999369 分钟前
html如何修改备注
jvm·数据库·python
京师20万禁军教头9 分钟前
29面向对象(中级)-继承
java
214396514 分钟前
HTML怎么创建时间轴布局_HTML结构化时间线写法【方法】
jvm·数据库·python
沐知全栈开发14 分钟前
CSS Backgrounds (背景)
开发语言
小草cys14 分钟前
树莓派4b + USRP B210 搭建反无人机(反无)系统( HTML + CDN )
开发语言·python·机器学习
gmaajt14 分钟前
HTML函数开发需要SSD吗_SSD对HTML函数开发效率影响【详解】
jvm·数据库·python
LiAo_1996_Y15 分钟前
p标签能嵌套div吗_HTML块级元素嵌套规则【解答】
jvm·数据库·python
2301_8166602117 分钟前
c++怎么将纯C的FILE-升级为C++的fstream_流缓冲绑定技巧【详解】
jvm·数据库·python