1

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

Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
halloleo
  • 9,216
  • 13
  • 64
  • 122
  • 1
    There is a typo, use `data -> data[1]` instead of `data -> [data[1]]`. – Nikolas Charalambidis Aug 16 '22 at 07:10
  • @NikolasCharalambidis No, that was intentional (although it _is_ a syntax error). Without the second brackets you go to `Map` (which gives you a type error), because the left side of the equal sign asks for`Map` – halloleo Aug 16 '22 at 07:13
  • So please, edit the answer. It is really not clear what is the problem. – Nikolas Charalambidis Aug 16 '22 at 07:21
  • @NikolasCharalambidis The problem is how to initialise `Map` via `Collectors.toMap`. I have edited the question to make this clearer. – halloleo Aug 16 '22 at 07:25
  • So you want each value of the map to be a string array with one string only? – Sweeper Aug 16 '22 at 07:27
  • @Sweeper Yes, exactly! The map key come from the 1st part of the stream tuple and the 2nd part of the stream tuple is used for the one string in the map values array. – halloleo Aug 16 '22 at 07:30
  • 1
    Does [this](https://stackoverflow.com/q/1154008/5133585) answer your question? – Sweeper Aug 16 '22 at 07:31
  • 2
    Do you want `Map map = Stream.of(...).collect(Collectors.toMap(data -> data[0], data -> new String[] {data[1]}));`? – Nikolas Charalambidis Aug 16 '22 at 07:33
  • @NikolasCharalambidis Yes, thank you. That's exactly it. I've tested it and it works perfectly. Thanks for "sticking with" my issue. – halloleo Aug 16 '22 at 07:36
  • @NikolasCharalambidis Do you want to make a answer out of this? If not, I'm happy do do it for you. – halloleo Aug 16 '22 at 07:37

1 Answers1

2

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]}));
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183