我想使用回调从 Java 列表中获取一个元素(不是索引)。
在 JavaScript 中,有一个 Array.prototype.find
方法可以做到这一点。
例如:
let match = [1, 2, 3, 4, 5].find((num) => num === 3);
console.log(match); // 3
Java 有等效的吗?
最佳答案
您可以使用 Java Stream API 来执行此操作。
import java.util.List;
public class Main {
public static void main(String[] args) {
int x = List.of(10, 20, 30, 40, 50).stream().filter(n -> (n == 30)).findAny().orElse(-1);
System.out.println(x);
int y = List.of(10, 20, 30, 40, 50).stream().filter(n -> (n == 3)).findAny().orElse(-1);
System.out.println(y);
}
}
输出:
30
-1
使用findAny() or findFirst()根据您的要求。
关于javascript - 使用 lambda/callback 从列表中获取元素 - 相当于 Array.prototype.find() 的 JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61123687/