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

10
  • 1
    There is a typo, use data -> data[1] instead of data -> [data[1]]. Commented Aug 16, 2022 at 7:10
  • @NikolasCharalambidis No, that was intentional (although it is a syntax error). Without the second brackets you go to Map<String, String> (which gives you a type error), because the left side of the equal sign asks forMap<String, String[]> Commented Aug 16, 2022 at 7:13
  • So please, edit the answer. It is really not clear what is the problem. Commented Aug 16, 2022 at 7:21
  • 1
    Does this answer your question? Commented Aug 16, 2022 at 7:31
  • 2
    Do you want Map<String, String[]> map = Stream.of(...).collect(Collectors.toMap(data -> data[0], data -> new String[] {data[1]}));? Commented Aug 16, 2022 at 7:33

1 Answer 1

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]}));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.