- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
假设我们有这段无聊的代码,我们都必须使用:
ArrayList<Long> ids = new ArrayList<Long>();
for (MyObj obj : myList){
ids.add(obj.getId());
}
切换到 Java 8 后,我的 IDE 告诉我可以用 collect call
替换此代码,它会自动生成:
ArrayList<Long> ids = myList.stream().map(MyObj::getId).collect(Collectors.toList());
但是它给了我这个错误:
collect(java.util.stream.Collector) in Steam cannot be applied to: (java.util.stream.Collector, capture, java.util.List>)
我尝试强制转换参数,但它给了我未定义的 A
和 R
,并且 IDE 没有提供更多建议。
我很好奇您如何在这种情况下使用 collect call
,但我找不到任何可以正确指导我的信息。有人能解释一下吗?
最佳答案
问题在于 Collectors.toList
,毫不奇怪,返回 List<T>
.不是 ArrayList
.
List<Long> ids = remove.stream()
.map(MyObj::getId)
.collect(Collectors.toList());
编程到 interface
.
来自文档:
Returns a
Collector
that accumulates the input elements into a newList
. There are no guarantees on the type, mutability, serializability, or thread-safety of theList
returned; if more control over the returned List is required, usetoCollection(Supplier)
.
强调我的 - 你甚至不能假设 List
返回是可变的,更不用说它属于特定类了。如果您想要 ArrayList
:
ArrayList<Long> ids = remove.stream()
.map(MyObj::getId)
.collect(Collectors.toCollection(ArrayList::new));
另请注意,习惯上使用 import static
使用 Java 8 Stream
API 所以添加:
import static java.util.stream.Collectors.toCollection;
(我讨厌星号 import static
,它只会污染命名空间并增加困惑。但是选择性 import static
,尤其是使用 Java 8 实用程序类,可以大大减少冗余代码)
会导致:
ArrayList<Long> ids = remove.stream()
.map(MyObj::getId)
.collect(toCollection(ArrayList::new));
关于java - 如何在 Java 8 中使用对方付费电话?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26905312/
我是一名优秀的程序员,十分优秀!