当前位置:网站首页>Stream通过findFirst()查找满足条件的一条数据
Stream通过findFirst()查找满足条件的一条数据
2022-08-10 12:52:00 【李长渊哦】
Stream通过findFirst查找满足条件的一条数据
一、Stream通过findFirst()查找满足条件的一条数据
1、案例
如果取得第一个元素,则用findFirst()
最后提取元素的时候,可以用:get或者orElse(null)
这里要注意的是,规范用法是orElse(null)
@Test
void test1() {
ArrayList<People> peopleList = Lists.newArrayList();
peopleList.add(new People(1, "小王", 1));
peopleList.add(new People(3, "小李", 3));
peopleList.add(new People(2, "小张", 2));
peopleList.add(new People(4, "小皇", 4));
People people = peopleList.stream().filter(c -> c.getJgid() % 2 == 0).findFirst().orElse(null);
System.out.println(people);
}

2、其他
Stream 的findFirst方法在此流中查找第一个元素作为 Optional 。
如果流中没有元素, findFirst 返回空的 Optional 。
如果流没有顺序,那么 findFirst 可以选择任何元素。
如果 findFirst 选择的元素为null,它将抛出 NullPointerException 。
package com.concretepage;
import java.util.stream.Stream;
public class FindFirstDemo4 {
public static void main(String[] args) {
Stream.of(null, "A").
findFirst().ifPresent(s -> System.out.println(s));
}
}
输出将为NullPointerException。
边栏推荐
- ABAP 里文件操作涉及到中文字符集的问题和解决方案试读版
- CodeForces - 834C
- Codeforces Round #276 (Div. 1) D. Kindergarten
- Keithley DMM7510 accurate measurement of ultra-low power consumption equipment all kinds of operation mode power consumption
- Reversing words in a string in LeetCode
- 大佬们有遇到过这个问题吗? MySQL 2.2 和 2.3-SNAPSHOT 都这样,貌似是
- 【iOS】Organization of interviews
- 山水的高度
- 进程和计划任务管理
- 【黑马早报】雷军称低谷期曾想转行开酒吧;拜登正式签署芯片法案;软银二季度巨亏230亿美元;北京市消协约谈每日优鲜...
猜你喜欢

表中存在多个索引问题? - 聚集索引,回表,覆盖索引

LeetCode中等题之搜索二维矩阵

Detailed explanation of es6-promise object

Redis 定长队列的探索和实践

Interface Automation Testing Basics
![ArcMAP出现-15的问题无法访问[Provide your license server administrator with the following information:Err-15]](/img/da/b49d7ba845c351cefc4efc174de995.png)
ArcMAP出现-15的问题无法访问[Provide your license server administrator with the following information:Err-15]

kubernetes介绍

3DS MAX 批量导出文件脚本 MAXScript 带界面

Basic knowledge of switches

Open Office XML 格式里如何描述多段具有不同字体设置的段落
随机推荐
rpn:def concat_box_prediction_layers
2022-08-09:以下go语言代码输出什么?A:否,会 panic;B:是,能正确运行;C:不清楚,看投票结果。 package main import ( “fmt“ “syn
想问下大佬们 ,cdc oracle初始化一张300万的表任务运行着后面就这个错 怎么解决哇
Short read or OOM loading DB. Unrecoverable error, aborting now
jenkins数据迁移和备份
Redis上云迁移实践
AtCoder Beginner Contest 077 D - Small Multiple
LeetCode中等题之颠倒字符串中的单词
Basic knowledge of switches
C# WPF image is displayed without problems, but the solution does not display the image at runtime
【ECCV 2022|百万奖金】PSG大赛:追求“最全面”的场景理解
11 + chrome advanced debugging skills, learn to direct efficiency increases by 666%
Proprietary cloud ABC Stack, the real strength!
娄底农产品检验实验室建设指南盘点
Ethernet channel Ethernet channel
Solution for "Certificate not valid for requested usage" after Digicert EV certificate signing
Interface Automation Testing Basics
需要被记录的OpenStack相关的命令_自己用
代码随想录笔记_动态规划_70爬楼梯
Codeforces Round #276 (Div. 1) D. Kindergarten