问题描述
// given a set of Item objects, group them by the managers of creator and owners
Map<String, List<Item>> managersItems =
itemSet.parallelStream().flatMap(item -> {
// get the list of the creator and owners
List<String> users = new ArrayList();
users.add(item.getCreator());
users.addAll(item.getOwners());
return Stream.of(users.toArray(new String[] {})).map(user -> {
LdapUserInfo ldapUser = LdapUserInfoFactory.create(user);
String manager = ldapUser.getManager();
return new AbstractMap.SimpleImmutableEntry<String, Item(manager, item);
});
}).collect(
Collectors.groupingBy(Map.Entry::getKey, Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
此代码在Eclipse Mars中编译良好,但在Eclipse Luna中获得以下错误:
This code compiles fine in Eclipse Mars, but gets the following eror in Eclipse Luna:
如果我没有分配使用 Map< String,List< Item>>返回
,错误在 Map
在Eclipse Luna中的managersItem = Map.Entry :: getKey
和 Map.Entry :: getValue
带消息的语句:
If I do not assign the returned to a Map
with Map<String, List<Item>> managersItem =
in Eclipse Luna, the error is at Map.Entry::getKey
and Map.Entry::getValue
statement with message:
什么我做错了吗?
推荐答案
你没有做错任何事.Eclipse编译器存在导致这些问题的类型推断问题。如果Luna兼容性很重要,则必须向lambda表达式添加显式类型。例如,尝试 Map.Entry ::< String,Item> getKey
You didn't do anything wrong. Eclipse compiler has problems with type inference that causes these issues. If Luna compatibility is important, you will have to add explicit types to lambda expressions. Try, for example, Map.Entry::<String,Item>getKey
另一方面,没有必要将 List
转换为数组来流式传输。你可以直接调用 users.stream()
。但是甚至不需要创建 List
。你可以使用 Stream.concat (Stream.of(item.getCreator()),item.getOwners()。stream())
而不是(g咆哮,这有点笨拙)。
On another note, it's not necessary to convert a List
to array to stream it. You can directly call users.stream()
. But even creating the List
isn't necessary. You can use Stream.concat(Stream.of(item.getCreator()), item.getOwners().stream())
instead (granted, it's a bit unwieldy).
最后(最重要的是),避免使用带阻塞代码的 parallelStream
,例如在外部查找数据系统。并行流旨在处理CPU绑定的任务。
Finally (and most importantly), avoid using parallelStream
with blocking code, such as looking up data in an external system. Parallel streams are designed to handle CPU-bound tasks.
这篇关于Java 8 Stream flatMap和group by code编译器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!