java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to convert an array to a Map?

This example use the Apache commons-lang's ArrayUtils class to convert a two dimensional array to a Map object.

package com.javacoderanch.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", "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"));
    }
}