veruyi
veruyi

Reputation: 93

Java 8 Stream List into map with identical values

I'm in a bizarre situation. Is there anyway to stream a List to a map with identical values?

i.e.

let a be of type Map< Integer, List< String > >

let's say b is just a list of integers that correspond to the keys of a.

b.stream().map(x ->
    a.get(x).stream()
        .collect(
            Collectors.toMap(i -> i, x);
        )
);

I want a map where all the values are an x and all the keys are from the values in b.

The above function is supposed to return a Stream< List< Map< String, Int > > > (obviously it doesn't work)

Upvotes: 2

Views: 2594

Answers (1)

flakes
flakes

Reputation: 23624

The second value in the toMap method needs to be a lambda as well (ie it needs to satisfy the interface Function<? super T, ? extends U>, where T is the type for objects in the b stream and U is the type for values in the resulting map):

Map<Integer, List<String>> a = ...
List<Integer> b = ...
Stream<Map<String, Integer>> c = b.stream().map(x ->
        a.get(x).stream()
                .collect(Collectors.toMap(i -> i, i -> x)));

Upvotes: 3

Related Questions