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 of ArrayUtils class 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.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button