1

I have a class like this:

public class A {
    private List<String> stringList;
    private String someString;
}

I have a list of these objects like so:

List<A> list = //some method to generate list

I want to conver this to a Map<String, String> where each string in the stringList maps to the same someString value (like a multimap). How can I do this using java 8 stream?

I could convert this to a flat map like so:

list.stream.flatMap(....

But I'm not sure where to go from there.

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
Richard
  • 5,840
  • 36
  • 123
  • 208

3 Answers3

3

Try this.

Map<String, String> r = list.stream()
    .flatMap(a -> a.stringList.stream()
        .map(k -> new AbstractMap.SimpleEntry<>(k, a.someString)))
    .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));
0

This has been answered here or here. Basically, you'll be creating a hashmap to your list, you should avoid doing so if your list is large.

Community
  • 1
  • 1
Seymore
  • 30
  • 3
0

I hope this helps.

List<String> fruits = Arrays.asList("Apple", "Orange", "Grape");
Map<String, String> myMap = fruits.stream().collect(Collectors.toMap(String::toString, String::toString));
myMap.forEach((k,v)->System.out.println("key : " + k + " value : " + v));