当前位置:网站首页>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。
边栏推荐
- shell:正则表达式及三剑客grep命令
- Inventory of Loudi Agricultural Products Inspection Laboratory Construction Guidelines
- wirshark 常用操作及 tcp 三次握手过程实例分析
- 一个 CRM One Order Application log 的单元测试报表
- 3DS MAX 批量导出文件脚本 MAXScript 带界面
- ABAP 里文件操作涉及到中文字符集的问题和解决方案试读版
- 浙大、阿里提出DictBERT,字典描述知识增强的预训练语言模型
- A detailed explanation of implementation api embed
- C# InitializeComponent() does not exist in the current context
- sprintboot项目通过interceptor和filter实现接入授权控制
猜你喜欢

中科院深圳先进技术院合成所赵国屏院士组2022年招聘启事

没有接班人,格力只剩“明珠精选”

Keithley DMM7510精准测量超低功耗设备各种运作模式功耗

Short read or OOM loading DB. Unrecoverable error, aborting now

Solution for "Certificate not valid for requested usage" after Digicert EV certificate signing

bgp dual plane experiment routing strategy to control traffic

LeetCode·每日一题·640.求解方程·模拟构造
![[Study Notes] Persistence of Redis](/img/e4/d3c09754ca5ac4fdad2653ccca6d82.png)
[Study Notes] Persistence of Redis

Detailed explanation of es6-promise object

Proprietary cloud ABC Stack, the real strength!
随机推荐
想通这点,治好 AI 打工人的精神内耗
MYSQL误删数据恢复
Jenkins修改端口号, jenkins容器修改默认端口号
来看Prada大秀吗?在元宇宙里那种!
九宫格抽奖动效
LeetCode·297.二叉树的序列化与反序列化·DFS·BFS
X5WebView使用
Reversing words in a string in LeetCode
广东10个项目入选工信部2021年物联网示范项目名单
Basic knowledge of switches
鸿蒙开发从hello world开始
ABAP 里文件操作涉及到中文字符集的问题和解决方案试读版
Nanodlp v2.2/v3.0光固化电路板,机械开关/光电开关/接近开关的接法和系统状态电平设置
递归递推之Fighting_小银考呀考不过四级
ArcMAP出现-15的问题无法访问[Provide your license server administrator with the following information:Err-15]
CodeForces-834C
[Advanced Digital IC Verification] Difference and focus analysis between SoC system verification and IP module verification
How to describe multiple paragraphs with different font settings in Open Office XML format
Drive IT Modernization with Low Code
Ethernet channel Ethernet channel