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

}
相关推荐
SongYuLong的博客1 小时前
C# WPF编程-边框控件(Border)
开发语言·c#·wpf
活跃家族1 小时前
Python的类和对象(4)
linux·开发语言·python
小小鸭程序员2 小时前
Spring Boot 整合 Redis 使用教程
java·spring boot·redis·mysql·spring
谷晓光2 小时前
python打印输出到文件
java·linux·python
L_cl6 小时前
【Python 算法零基础 1.线性枚举】
python·算法
优雅的落幕6 小时前
前端---初识HTML(前端三剑客)
java·前端·javascript·css·html
百香果果ccc8 小时前
Maven的继承和聚合
java·hive·maven
极客先躯8 小时前
高级java每日一道面试题-2025年3月04日-微服务篇[Eureka篇]-Eureka是什么?
java·微服务·eureka·集群部署·健康检查·组件和架构·自我保护机制
apcipot_rain8 小时前
【密码学——基础理论与应用】李子臣编著 第四章 SM4分组密码算法 课后习题
python·密码学
幸好我会魔法8 小时前
RabbitMQ实现定时/延迟任务
java·rabbitmq·java-rabbitmq