VOOZH about

URL: https://dzone.com/articles/java-convert-map-to-array-snippet

⇱ Java Convert Map to Array [Snippet]


Related

  1. DZone
  2. Data Engineering
  3. Data
  4. Java Convert Map to Array [Snippet]

Java Convert Map to Array [Snippet]

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

By Dec. 10, 18 · Code Snippet
Likes
Comment
Save
21.4K Views

Join the DZone community and get the full member experience.

Join For Free

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]

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.

Related

  • Immutable Objects Using Record in Java
  • Floyd's Cycle Algorithm for Fraud Detection in Java Systems
  • How to Convert Files to Thumbnail Images in Java
  • Understanding Floating-Point Precision Issues in Java

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

Let's be friends: