Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

Atomist automates your software deliver experience. It's how modern teams deliver modern software.

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);
        System.out.println(Arrays.toString(targetArray));
    }
}


Here is the output:

[ABC, PQR, XYZ]


Similar Collections Examples [Snippet]

Get the open source Atomist Software Delivery Machine and start automating your delivery right there on your own laptop, today!

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

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}