Java Convert Map to Array Example

Let's write a Java program to convert Map values to String array.

Convert Map Values to Array Example

First, let’s look at converting the values of the Map into an array, using plain java:
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));
    }
}
Output:
[ABC, PQR, XYZ]

Similar Collections Examples [Snippet]

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Comments