Convert 2D String Static Array to HashMap

What is the easiest way to convert a 2D array of strings to a HashMap?

For example, take this:


final String[][] sheetMap = { /* XSD Name,  XSL Sheet Name */
                              {"FileHeader", "FileHeader"}, 
                              {"AccountRecord", "AccountRecord"}, 
                              {"DriverCardRecord", "DriverCardRecord"}, 
                              {"AssetCardRecord", "AssetCardRecord"},
                              {"SiteCardRecord", "SiteCardRecord"}
                            };

Most likely it will be loaded from a file and there will be much more.

+5
source share
7 answers
final Map<String, String> map = new HashMap<String, String>(sheetMap.length);
for (String[] mapping : sheetMap)
{
    map.put(mapping[0], mapping[1]);
}
+20
source

If you just want to initialize your map in a convenient way, you can use double brace binding :

Map<String, String > sheetMap = new HashMap<String, String >() {{
   put( "FileHeader", "FileHeader" ); 
   put( "AccountRecord", "AccountRecord" ); 
   put( "DriverCardRecord", "DriverCardRecord" ); 
   put( "AssetCardRecord", "AssetCardRecord" );
   put( "SiteCardRecord", "SiteCardRecord" );
}};
+4
source

:

String[][] arr = // your two dimensional array
Map<String, String> arrMap = Arrays.stream(arr).collect(Collectors.toMap(e -> e[0], e -> e[1]));

// Sanity check!
for (Entry<String, String> e : arrMap.entrySet()) {
    System.out.println(e.getKey() + " : " + e.getValue());
}
+3

; , ! , , . HashMap , .

+2

:

 import static java.util.Arrays.stream;
 import static java.util.stream.Collectors.toMap;
 import java.util.Map;

     ...

 public static Map<String, String> asMap(String[][] data) {
     return stream(data).collect(toMap( m->m[0], m->m[1] ));
 }

     ...
+2

, , , , Java 8:

String[][] arr = {{"key", "val"}, {"key2", "val2"}};
HashMap<String, String> map = Arrays.stream(arr)
        .collect(HashMap<String, String>::new,
                (mp, ar) -> mp.put(ar[0], ar[1]),
                HashMap<String, String>::putAll);

Java 8 Stream , , :

  • Arrays.stream Stream<String[]>.
  • collect Stream , . . , , , , HashMap. - , - Stream, put , , . - , , , - , JVM HashMap (in this case, or any other target in another case), and then you need to combine them into one, which is mainly intended for asynchronous execution, although this usually does not happen.
+1
source

Java 8 way

  public static Map<String, String> convert2DArrayToMap(String[][] data){
    return Arrays.stream(data).collect(Collectors.toMap(m -> m[0], m -> m[1]));
  }

with cycle

public static Map<String, String> convert2DArrayToMap(String[][] data)
  {
    Map<String, String> map = new HashMap<>();
    for (String[] m : data)
    {
      if (map.put(m[0], m[1]) != null)
      {
        throw new IllegalStateException("Duplicate key");
      }
    }
    return map;
  }
0
source

All Articles