Java 使用 lambda 表达式从对象列表中选择对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24799650/
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
Select Object from Object' s list using lambda expression
提问by Tinwor
Hi guys I have a List<User>and I want add a method that return a particular User found using Id. I want make that using lambda expression so I have tried this but it doesn't work.
大家好,我有一个List<User>,我想添加一个方法来返回使用 Id 找到的特定用户。我想使用 lambda 表达式来实现它,所以我试过这个,但它不起作用。
...
List<User> user = users.stream().filter(x -> x.id == id).collect(Collectors.toList());
return user[0];
This code dosen't compile and give me these errors:
此代码无法编译并给我以下错误:
The method stream() is undefined for the type List<User>
Lambda expressions are allowed only at source level 1.8 or above *
Collectors cannot be resolved
- I'm using eclipse 4.4.3 Kepler and I have installed java 8 in the machine and the plugin for working with java8 in eclipse
- 我正在使用 eclipse 4.4.3 Kepler 并且我已经在机器中安装了 java 8 和用于在 eclipse 中使用 java8 的插件
采纳答案by kajacx
Advice: If you want just first element matchig a condition, don't collect all elements to list (it's a bit overkill), use findFirst()method instead:
建议:如果你只想匹配一个条件的第一个元素,不要收集所有元素来列出(这有点矫枉过正),findFirst()而是使用方法:
return users.stream().filter(x -> x.id == id).findFirst().get();
Note that findFirst()will return an Optionalobject, and get()will throw an exception if there is no such element.
请注意,findFirst()将返回一个Optional对象,get()如果没有这样的元素,将抛出异常。
回答by Konstantin Yovkov
You have two problems.
你有两个问题。
You have to enable Java 1.8. Compliance Level in Eclipse and successfully import the Java8 specific classes/interfaces. What you have to do is the following:
- Right-click on the project and select
Properties - Select
Java Compilerin the window that has been opened - Under
JDK Complianceunselect theUse compliance level from execution environment....checkbox and then select1.8from theCompliance leveldropdown. - Click
OKand your done.
- Right-click on the project and select
您必须启用 Java 1.8。Eclipse 中的合规性级别并成功导入 Java8 特定类/接口。您需要做的是:
- 右键单击项目并选择
Properties Java Compiler在已经打开的窗口中选择- 在
JDK Compliance取消选中Use compliance level from execution environment....复选框,然后1.8从Compliance level下拉列表中选择。 - 单击
OK并完成。
- 右键单击项目并选择
After you do that, you will notice that the returnstatement is not compiling. This is because the Listobject in Java is not an array, and therefore statements like user[0]are invalid for lists. What you have to do is:
执行此操作后,您会注意到该return语句未编译。这是因为ListJava 中的对象不是数组,因此像这样的语句user[0]对于列表是无效的。你需要做的是:
return user.get(0);

