java - 如何在 Java 8 中使用对方付费电话?

标签 java java-8 java-stream collect

假设我们有这段无聊的代码,我们都必须使用:

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>)

我尝试强制转换参数,但它给了我未定义的 AR,并且 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 new List. There are no guarantees on the type, mutability, serializability, or thread-safety of the List returned; if more control over the returned List is required, use toCollection(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/

相关文章:

java - 按值对 AtomicLongMap 进行排序

java - 如何防止 eclipse 中出现意外的特殊符号

java - 为什么静态初始化程序中带有 lambda 的并行流会导致死锁?

Java 8 - 使用 Doclet 的自定义 JavaDoc 检查

java - Stream if not null 并获取第一个对象

java - 将流转换为字符串...(3 点)

java - AppCompatActivity导致CustomView onConfigurationChanged方法未调用

java - 无法使用itext和java对pdf进行数字签名

java - 供供应商生成 IntStream 的 Lambda 表达式

流并行中的 Java 8 流