Convert Array to Map in Java.
This example use the Apache Commons ArrayUtils class to convert a two dimensional array to a Map object.
This example shows how to convert Array to Map in Java. Apache Commons ArrayUtils toMap method converts two dimentional Array to Map object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
import java.util.Map; import org.apache.commons.lang.ArrayUtils; public class ArrayToMapExample { public static void main(String[] args) { // // A two dimensional array of countries capital. // String[][] countries = { { "United States", "New York" }, { "United Kingdom", "London" }, { "Netherlands", "Amsterdam" }, { "Japan", "Tokyo" }, { "France", "Paris" } }; // // To convert an array to a Map each array elements must // be an array with at least two elements where the first // element will be the key and the second element will be // the value. // Map countryCapitals = ArrayUtils.toMap(countries); System.out.println("Capital of Japan is " + countryCapitals.get("Japan")); System.out.println("Capital of France is " + countryCapitals.get("France")); } } |