PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, September 20, 2022

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

 September 20, 2022     collectors, hashmap, java, java-8, lambda     No comments   

Issue

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


Answered By - Nikolas Charalambidis
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing