Java Convert Map to Array [Snippet]
Check out this code example to learn more about converting to arrays.
Join the DZone community and get the full member experience.
Join For FreeLet's write a Java program that converts Map values to the String array.
Convert Map Values to Array Example
package net.javaguides.corejava;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
public class MapToArrayExample {
public String[] mapValuesToArray(Map < Integer, String > sourceMap) {
Collection < String > values = sourceMap.values();
String[] targetArray = values.toArray(new String[values.size()]);
return targetArray;
}
public static void main(String[] args) {
MapToArrayExample mapToArrayExample = new MapToArrayExample();
Map < Integer, String > sourceMap = new HashMap < > ();
sourceMap.put(100, "ABC");
sourceMap.put(101, "PQR");
sourceMap.put(102, "XYZ");
String[] targetArray = mapToArrayExample.mapValuesToArray(sourceMap);
System.out.println(Arrays.toString(targetArray));
}
}
Here is the output:
[ABC, PQR, XYZ]
Similar Collections Examples [Snippet]
Java (programming language)
Convert (command)
Data structure
Published at DZone with permission of Ramesh Fadatare. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments