This example uses the Apache Commons Lang’s ArrayUtils.toMap()
method to convert a two-dimensional array into a Map
object.
To convert a two-dimensional array into a Map
object, each element of the two-dimensional array 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.
package org.kodejava.commons.lang;
import java.util.Map;
import org.apache.commons.lang3.ArrayUtils;
public class ArrayToMapExample {
public static void main(String[] args) {
// A two-dimensional array of country capital.
String[][] countries = {{"United States", "Washington, D.C."},
{"United Kingdom", "London"},
{"Netherlands", "Amsterdam"},
{"Japan", "Tokyo"},
{"France", "Paris"}};
// Convert an array to a Map.
Map<Object, Object> capitals = ArrayUtils.toMap(countries);
for (Object key : capitals.keySet()) {
System.out.printf("%s is the capital of %s.%n", capitals.get(key), key);
}
}
}
The result of our code snippet:
London is the capital of United Kingdom.
Amsterdam is the capital of Netherlands.
Paris is the capital of France.
Washington, D.C. is the capital of United States.
Tokyo is the capital of Japan.
Maven Dependencies
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.14.0</version>
</dependency>
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024