2

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)

veruyi
  • 93
  • 5
  • Can you show sample input and output data? – shmosel Jan 12 '17 at 00:57
  • 1
    Your posted code should produce a stream of maps, each mapping all keys to a single value. I'm not sure why you would want that, or where the list comes into the result. – shmosel Jan 12 '17 at 01:02
  • 2
    The second value in `toMap` needs to be a lambda as well `Collectors.toMap(i -> i, i -> x)` – flakes Jan 12 '17 at 01:02
  • 2
    The above looks to me like it'd create a **stream** of `Map`. You could make that into a `List>` but adding another `collect` call before the final `;`. Not sure what it'd mean for it to be a stream of list of map - that seems like one too many collection/stream. – Oliver Dain Jan 12 '17 at 01:04
  • @flakes thank you. exactly what I needed. – veruyi Jan 12 '17 at 01:07
  • 1
    This looks like an XY problem. If all you want is “a map where … all the keys are from the values in b”, you probably want just `Map< Integer, List< String > > result = b.stream().collect( Collectors.toMap(i -> i, a::get) );`, assuming that “`x`” is the `List`. Otherwise, you should first describe your actual problem correctly. – Holger Jan 12 '17 at 14:00

1 Answers1

3

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)));
flakes
  • 21,558
  • 8
  • 41
  • 88