One-to-one map with Java streams

扶醉桌前 提交于 2019-12-03 13:55:45

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()));
}

Note from the javadoc

If the mapped keys contains duplicates (according to Object.equals(Object)), an IllegalStateExceptionis thrown when the collection operation is performed. If the mapped keys may have duplicates, use toMap(Function, Function, BinaryOperator) instead.

groupingBy() collects items (plural, as a List) by a key.

You want toMap():

public static Map<String, Item> streamToOneToOne(Stream<Item> itemStream) {
    return itemStream.collect(toMap(Item::getUuid, Function.identity()));
}

Maybe try

itemStream.stream().collect(toMap(Item::getUuid,Functions.identity());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!