在使用 Stream API 获取一对一映射时遇到一点问题。基本上,假设你有一节课。
public class Item {
private final String uuid;
private Item(String uuid) {
this.uuid = uuid;
}
/**
* @return universally unique identifier
*/
public String getUuid() {
return uuid;
}
}
我想要一个 Map<String, Item>
方便查找。但是给出一个 Stream<Item>
似乎没有一种简单的方法可以达到 Map<String, Item>
.
显然,Map<String, List<Item>>
什么都不是:
public static Map<String, List<Item>> streamToOneToMany(Stream<Item> itemStream) {
return itemStream.collect(groupingBy(Item::getUuid));
}
这是更安全更一般的情况,但我们确实知道在这种情况下永远只会有一对一。虽然我找不到任何可以编译的东西——我一直在专门尝试处理 downstream
参数 Collectors.groupingBy
.像这样的东西:
// DOESN'T COMPILE
public static Map<String, Item> streamToOneToOne(Stream<Item> itemStream) {
return itemStream.collect(groupingBy(Item::getUuid, Function.identity()));
}
我错过了什么?
最佳答案
使用 Collectors#toMap(Function, Function)
,从每个 Item
的 uuid
和 Item
生成键作为值本身。
public static Map<String, Item> streamToOneToOne(Stream<Item> itemStream) {
return itemStream.collect(Collectors.toMap(Item::getUuid, Function.identity()));
}
来自 javadoc 的注释
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 - 与 Java 流的一对一映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31640588/