Using Java streams to convert collection to map: how to put predefined Enum as value

Kate Le :

I have a collection of Long, and for a reason I need to create a map from this collection, which has the elements of the collection as keys, and 1 predefined Enum as value (all keys have the same value).

I am trying to achieve this with Streams, like below:

private Map<Long, Marker> mapMarker(Collection<Long> ids, Marker marker) {
    return ids.stream().collect(Collectors.toMap(Function.identity(), marker));
}

Compiler failed with this error:

no instance(s) of type variable(s) T, U exist so that Marker conforms to Function<? super T, ? extends U>

Could someone please explain to me why would it fails? Is there anyway to get the expected result with Streams?

Naman :

If Marker is the enum you want to map against ll the keys in ids, you can do it as:

return ids.stream().collect(Collectors.toMap(Function.identity(), id -> marker));

You were quite close, just that id -> marker is a Function as expected for Collectors.toMap

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=76756&siteId=1