Search code examples
javalambdajava-8hashmapcollectors

How to initialise in Java a Map<String, String[]> object via the Collectors.toMap() method


I want to initialize a Map<String, String[]> object in one logical line with the Collectors.toMap() method where I provide a stream of string tuples. Each tuple then is used via lambdas to fill the key of a map entry with the first part of the tuple and to fill the first slot of the entry values with the second part of the tuple.

Because this sound complicated, here is the code I've tried so far:

Map<String, String[]> map = Stream.of(new String[][] {
  { "Hello", "World" }, 
  { "John", "Doe" }, 
}).collect(Collectors.toMap(data -> data[0], data -> [data[1]] ));

This is obviously syntacitially wrong. So the question is "How do I initialise a Map<String, String[]> object via the Collectors.toMap() method? correctly


Solution

  • If the desired output is Map<String, String[]>, then you have to instantiate the String array as a value in the toMap collector:

    Map<String, String[]> map = Stream.of(
            new String[][] {
                    { "Hello", "World" },
                    { "John", "Doe" },
            })
            .collect(Collectors.toMap(
                    data -> data[0], 
                    data -> new String[] {data[1]}));