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

Time:08-16

I want to initialise 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 sounds complicates, here 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

CodePudding user response:

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]}));
  • Related