Kate Le
Kate Le

Reputation: 43

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

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?

Upvotes: 4

Views: 124

Answers (2)

Naman
Naman

Reputation: 31868

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

Upvotes: 3

nbrooks
nbrooks

Reputation: 18233

The parameters to Collectors.toMap should be functions that convert the input to your desired output. You can use a placeholder variable (such as i) to represent your input. For example, for the identity function, take input i and return i. For mapping every item to marker, take input i and return marker:

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

Upvotes: 2

Related Questions