One-to-one map with Java streams

半城伤御伤魂 提交于 2019-12-21 01:06:11

问题


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

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>.

Obviously, Map<String, List<Item>> ain't no thing:

public static Map<String, List<Item>> streamToOneToMany(Stream<Item> itemStream) {
    return itemStream.collect(groupingBy(Item::getUuid));
}

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

What am I missing?


回答1:


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.




回答2:


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



回答3:


Maybe try

itemStream.stream().collect(toMap(Item::getUuid,Functions.identity());


来源:https://stackoverflow.com/questions/31640588/one-to-one-map-with-java-streams

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