lang3
Convert array to Map
In this example we shall show you how to convert an array to a Map. We are using the org.apache.commons.lang3.ArrayUtils class, that provides operations on arrays, primitive arrays (like int[]) and primitive wrapper arrays (like Integer[]). This class tries to handle null input gracefully. An exception will not be thrown for a null array input. To convert an array to a Map one should perform the following steps:
- Create a two-dimensional array of String items.
- Use
toMap(Object[] array)method ofArrayUtilsclass to convert the given array into a Map. - Print the values of the map,
as described in the code snippet below.
package com.javacodegeeks.snippets.core;
import org.apache.commons.lang3.ArrayUtils;
import java.util.Map;
public class Array2Map {
public static void main(String[] args) {
// Two dimensional array of items
String[][] arrayItems = {{"key0", "Item0"},
{"key1", "Item1"},
{"key2", "Item2"},
{"key3", "Item3"},
{"key4", "Item4"}};
// Convert to Map. The first index of each row of the array will be the key of the Item
Map mapItems = ArrayUtils.toMap(arrayItems);
// Print some value for testing
System.out.println("The item with key0 is : " + mapItems.get("key0"));
System.out.println("The item with key3 is : " + mapItems.get("key3"));
}
}
Output:
The item with key0 is : Item0
The item with key3 is : Item3
This was an example of how to convert an array to a Map in Java.
