How do I convert an array to a Map?

This example use 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.example.commons.lang;

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", "Washington, D.C."},
            {"United Kingdom", "London"},
            {"Netherlands", "Amsterdam"},
            {"Japan", "Tokyo"},
            {"France", "Paris"}};

        // Convert an array to a Map.
        Map 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

<!-- http://repo1.maven.org/maven2/commons-lang/commons-lang/2.6/commons-lang-2.6.jar -->
<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.6</version>
</dependency>

Wayan Saryada

Programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply