gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:38:16 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com