Java Convert Array to Map using Apache Commons Lang
Tags: ArrayUtils Apache Commons Apache Commons Lang array Map
In this Java tutorial we learn how to convert a given array into a Map object using ArrayUtils of Apache Commons Lang library.
How to add Apache Commons Lang 3 library to your Java project
To use the Apache Commons Lang 3 library in the Gradle build project, add the following dependency into the build.gradle file.
implementation 'org.apache.commons:commons-lang3:3.12.0'
To use the Apache Commons Lang 3 library in the Maven build project, add the following dependency into the pom.xml file.
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
To have more information about the Apache Commons Lang 3 library you can visit the library home page at commons.apache.org/proper/commons-lang/
How to convert Array to Map in Java
The Apache Commons Lang library provides the method ArrayUtils.toMap() to convert a given array into a Map object. Each element of the input array must be an array with at least two elements, the first element is used as key and the second element be used as a value. You can learn how to use the ArrayUtils.toMap() method via the below code example.
ConvertArrayToMap.java
import org.apache.commons.lang3.ArrayUtils;
import java.util.Map;
public class ConvertArrayToMap {
public static void main(String... args) {
String[][] arrayToConvert = new String[][] {
{"RED", "#FF0000"},
{"GREEN", "#00FF00"},
{"BLUE", "#0000FF"}
};
Map<Object, Object> resultMap = ArrayUtils.toMap(arrayToConvert);
System.out.println("Result " + resultMap.getClass() + " content:");
for (Map.Entry entry : resultMap.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
}
}
Result class java.util.HashMap content:
Key: RED, Value: #FF0000
Key: GREEN, Value: #00FF00
Key: BLUE, Value: #0000FF
Happy Coding 😊