Java - 使用条件和 Lambda 在数组中查找元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32262059/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 12:14:05  来源:igfitidea点击:

Java - Find Element in Array using Condition and Lambda

javaarrayslambdajava-8java-stream

提问by Joe Almore

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:

简而言之,我有这段代码,我想使用条件和 lambda 来获取数组的特定元素。代码将是这样的:

Preset[] presets = presetDALC.getList();
Preset preset = Arrays.stream(presets).select(x -> x.getName().equals("MyString"));

But obviously this does not work. In C# would be something similar but in Java, how do I do this?

但显然这行不通。在 C# 中会类似,但在 Java 中,我该怎么做?

采纳答案by CoderCroc

You can do it like this,

你可以这样做,

Optional<Preset> optional = Arrays.stream(presets)
                                   .filter(x -> "MyString".equals(x.getName()))
                                   .findFirst();

if(optional.isPresent()) {//Check whether optional has element you are looking for
    Preset p = optional.get();//get it from optional
}

You can read more about Optionalhere.

您可以Optional在此处阅读更多信息。

回答by Robby Cornelissen

Like this:

像这样:

Optional<Preset> preset = Arrays
        .stream(presets)
        .filter(x -> x.getName().equals("MyString"))
        .findFirst();

This will return an Optionalwhich might or might not contain a value. If you want to get rid of the Optionalaltogether:

这将返回一个Optional可能包含也可能不包含值的 。如果你想Optional完全摆脱:

Preset preset = Arrays
        .stream(presets)
        .filter(x -> x.getName().equals("MyString"))
        .findFirst()
        .orElse(null);

The filter()operation is an intermediate operation which returns a lazy stream, so there's no need to worry about the entire array being filtered even after a match is encountered.

filter()操作是一个返回惰性流的中间操作,因此即使遇到匹配项,也无需担心整个数组会被过滤。

回答by Andreas

Do you want first matching, or all matching?

你是要先匹配还是全部匹配?

String[] presets = {"A", "B", "C", "D", "CA"};

// Find all matching
List<String> resultList = Arrays.stream(presets)
                                .filter(x -> x.startsWith("C"))
                                .collect(Collectors.toList());
System.out.println(resultList);

// Find first matching
String firstResult = Arrays.stream(presets)
                           .filter(x -> x.startsWith("C"))
                           .findFirst()
                           .orElse(null);
System.out.println(firstResult);

Output

输出

[C, CA]
C