Java - 使用Condition和Lambda在Array中查找元素 [英] Java - Find Element in Array using Condition and Lambda
本文介绍了Java - 使用Condition和Lambda在Array中查找元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
简而言之,我有这段代码,我想使用条件和lambda获取数组的特定元素。代码如下:
In short, I have this code, and I'd like to get an specific element of the array using a condition and lambda. The code would be something like this:
Preset[] presets = presetDALC.getList();
Preset preset = Arrays.stream(presets).select(x -> x.getName().equals("MyString"));
但显然这不起作用。在C#中会有类似的东西,但在Java中,我该怎么做?
But obviously this does not work. In C# would be something similar but in Java, how do I do this?
推荐答案
你可以这样做,> p>
You can do it like this,
Optional<Present> optional = Arrays.stream(presents)
.filter(x -> "MyString".equals(x.getName()))
.findFirst();
if(optional.isPresent()) {//Check whether optional has element you are looking for
Present p = optional.get();//get it from optional
}
您可以阅读更多关于可选
此处。
You can read more about Optional
here.
这篇关于Java - 使用Condition和Lambda在Array中查找元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文