Java Convert Map to Array [Snippet]

DZone 's Guide to

Java Convert Map to Array [Snippet]

Check out this code example to learn more about converting to arrays.

· Java Zone ·
Free Resource

Let'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);

Here is the output:


Similar Collections Examples [Snippet]

array, code, code snippet, example, java, map, string, string array

Published at DZone with permission of Ramesh Fadatare . See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}