如何在Java 8中使用collect调用? [英] How to use collect call in Java 8?

查看:456
本文介绍了如何在Java 8中使用collect调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我们必须使用这段无聊的代码:

Lets say we have this boring piece of code that we all had to use:

ArrayList<Long> ids = new ArrayList<Long>();
for (MyObj obj : myList){
    ids.add(obj.getId());
}

切换到Java 8后,我的IDE告诉我我可以替换它代码收集调用,并自动生成:

After switching to Java 8, my IDE is telling me that I can replace this code with collect call, and it auto-generates:

ArrayList<Long> ids = myList.stream().map(MyObj::getId).collect(Collectors.toList());

然而它给我这个错误:


在Steam中的collect(java.util.stream.Collector)无法应用于:(java.util.stream.Collector,capture,java.util.List>)

collect(java.util.stream.Collector) in Steam cannot be applied to: (java.util.stream.Collector, capture, java.util.List>)

我尝试了这个参数,但它给了我未定义的 A R ,IDE没有提供更多建议。

I tried casting the parameter but its giving me undefined A and R, and the IDE isn't giving any more suggestions.

我很好奇你怎么能用收集电话在这种情况下,我找不到任何可以指导我的信息。任何人都可以解雇吗?

I'm curious as how can you use collect call in this scenario, and I couldn't find any information that could guide me properly. Can anyone shed a light?

推荐答案

问题在于 Collectors.toList ,而不是令人惊讶的是,返回列表< T> 。不是 ArrayList

List<Long> ids = remove.stream()
        .map(MyObj::getId)
        .collect(Collectors.toList());

编入界面

Program to the interface.

来自文档:


返回收集器将输入元素累积到新的
列表中。 无法保证类型,可变性,
可序列化或列表返回的线程安全性
;如果需要更多
控制返回的List,请使用
toCollection(Supplier)

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

Emphasis mine - you cannot even assume that the List returned is mutable, let alone that it is of a specific class. If you want an ArrayList:

ArrayList<Long> ids = remove.stream()
        .map(MyObj::getId)
        .collect(Collectors.toCollection(ArrayList::new));

另请注意,习惯上使用 import static 使用Java 8 Stream API,因此添加:

Note also, that it is customary to use import static with the Java 8 Stream API so adding:

import static java.util.stream.Collectors.toCollection;

(我讨厌加星标导入静态,它除了污染名称空间并添加混淆之外什么都不做。但是选择性 import static ,特别是使用Java 8实用程序类,可以大大减少冗余代码)

(I hate starred import static, it does nothing but pollute the namespace and add confusion. But selective import static, especially with the Java 8 utility classes, can greatly reduce redundant code)

会导致:

ArrayList<Long> ids = remove.stream()
        .map(MyObj::getId)
        .collect(toCollection(ArrayList::new));

这篇关于如何在Java 8中使用collect调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆