One-to-one map with Java streams

2020-06-03 10:01发布

问题:

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