使用Java流的一对一地图 [英] One-to-one map with Java streams
问题描述
使用Stream API获取一对一映射时遇到一些麻烦。基本上,假设你有一个班级。
Having a little trouble using the Stream API to get a one to one mapping. Basically, say you've got a class.
public class Item {
private final String uuid;
private Item(String uuid) {
this.uuid = uuid;
}
/**
* @return universally unique identifier
*/
public String getUuid() {
return uuid;
}
}
我想要映射< String,Item>
以便于查找。但鉴于 Stream< Item>
,似乎没有一种简单的方法可以达到 Map< String,Item>
。
I'd like a Map<String, Item>
for easy look up. But given a Stream<Item>
there doesn't seem a simple way to arrive at that Map<String, Item>
.
显然, Map< String,List< Item>>
并不是一件事:
public static Map<String, List<Item>> streamToOneToMany(Stream<Item> itemStream) {
return itemStream.collect(groupingBy(Item::getUuid));
}
这是更安全更普遍的情况,但我们做在这种情况下知道只会一对一。我找不到任何可编译的东西 - 我特意试图将下游
参数砸到 Collectors.groupingBy
。类似于:
That's the safer more general case, but we do know in this situation that there will only ever be one-to-one. I can't find anything that compiles though -- I've specifically been trying to muck with the downstream
parameter to Collectors.groupingBy
. Something like:
// DOESN'T COMPILE
public static Map<String, Item> streamToOneToOne(Stream<Item> itemStream) {
return itemStream.collect(groupingBy(Item::getUuid, Function.identity()));
}
我缺少什么?
推荐答案
使用 收集器#toMap(功能,功能)
,从每个项目
的 uuid
和项目$ c $生成密钥c>作为值本身。
Use the Collectors#toMap(Function, Function)
, generating the key from each Item
's uuid
and the Item
as the value itself.
public static Map<String, Item> streamToOneToOne(Stream<Item> itemStream) {
return itemStream.collect(Collectors.toMap(Item::getUuid, Function.identity()));
}
来自javadoc的注释
Note from the javadoc
如果映射的密钥包含重复项(根据
Object.equals(Object)
),则集合操作时,抛出IllegalStateException 。如果映射的键可能有
重复,请使用toMap(Function,Function,BinaryOperator)
。
If the mapped keys contains duplicates (according to
Object.equals(Object)
), anIllegalStateException
is thrown when the collection operation is performed. If the mapped keys may have duplicates, usetoMap(Function, Function, BinaryOperator)
instead.
这篇关于使用Java流的一对一地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!