<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>TreeMap &#8211; CodePills.com</title>
	<atom:link href="https://codepills.com/tag/treemap/feed/" rel="self" type="application/rss+xml" />
	<link>https://codepills.com</link>
	<description>Helping you make a better code</description>
	<lastBuildDate>Thu, 17 Jun 2021 11:07:30 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	
	<item>
		<title>How to convert a Map to an Array in Java</title>
		<link>https://codepills.com/how-to-convert-a-map-to-an-array-in-java/</link>
					<comments>https://codepills.com/how-to-convert-a-map-to-an-array-in-java/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Fri, 12 Mar 2021 13:35:50 +0000</pubDate>
				<category><![CDATA[Language basics]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[Collection]]></category>
		<category><![CDATA[conversion]]></category>
		<category><![CDATA[HashMap]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[LinkedHashMap]]></category>
		<category><![CDATA[Map]]></category>
		<category><![CDATA[TreeMap]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1182</guid>

					<description><![CDATA[This tutorial is about several approaches to converting Java's Map interface implementations into the Java array. <a href="https://codepills.com/how-to-convert-a-map-to-an-array-in-java/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>This tutorial is about several approaches to converting Java&#8217;s Map interface implementations into the Java array.</p>
<p><span id="more-1182"></span></p>
<h2>Introduction</h2>
<p>In order to turn Java <code>Map</code> to array, it always depend what you actually want to take from the <code>Map</code> itself. You can only want keys or values or transform key-value pairs on a completely different object while turning them into an array.</p>
<p><b>Note</b></p>
<p>We need to note, that in most of our examples we <b>will use</b> <code>HashMap</code> <b>implementation</b> as underlying layer upon which the algorithms are build. If the implementation change and it will affect the algorithm, it will be notably depicted and described.</p>
<h2>Map Map.Entry<K,V> to Array</h2>
<p>Our first approach is the simplest and probably covers most of the cases in real life. The approach obtains <code>Map.Entry<K,V></code> from <code>Map</code> and then turn the collection to an array.</p>
<p>We will use non-parametrized call of <code>Set.toArray()</code> for <code>Entry<K,V></code> collection. Let&#8217;s look at the example below:</p>
<pre><code class="language-java">// Method to convert Map entry set into an Array in Java
public static void entrySetToArray()
{
    final Map<String, String> map = new HashMap<>();

    map.put("John Doe", "555-869-759");
    map.put("Thomas Cook", "555-906-941");
    map.put("Paul Smith", "555-400-321");

    // Gets the Map entry set and turns it into an Array of Objects
    final Object[] objectArray = map.entrySet().toArray();

    System.out.println(Arrays.toString(objectArray));
}</code></pre>
<p><b>Output</b></p>
<pre><code class="language-java">[Paul Smith=555-400-321, John Doe=555-869-759, Thomas Cook=555-906-941]</code></pre>
<h2>Map Keys to Array</h2>
<p>Sometimes we want to map <code>Map</code> keys to an array. For this we need to use combination of <code>Map.keySet()</code> for obtaining keys and parametrized call of <code>Set.toArray(T[] a)</code> method for keeping a set of keys. Than we can turn key set to an <code>Array</code>.</p>
<pre><code class="language-java">// Method to convert Map keys into an Array in Java
public static void keySetToArray()
{
    final Map<String, String> map = new HashMap<>();<>

    map.put("John Doe", "555-869-759");
    map.put("Thomas Cook", "555-906-941");
    map.put("Paul Smith", "555-400-321");

    // Gets the Map set of keys which is turned to an Array of Strings
    String[] keys = map.keySet().toArray(new String[0]);

    System.out.println(Arrays.toString(keys));
}</code></pre>
<p><b>Output</b></p>
<pre><code class="language-java">[Paul Smith, John Doe, Thomas Cook]</code></pre>
<h2>Map Values to Array</h2>
<p>Other times, we want to map <code>Map</code> values to an array. For this we need to use combination of <code>Map.values()</code> for obtaining keys and parametrized call of <code>Collection.toArray(T[] a)</code> method for keeping a collection of values. Than we can turn value collection to an <code>Array</code>.</p>
<pre><code class="language-java">// Method to convert Map values into an Array in Java
public static void valuesCollectionToArray()
{
    final Map<String, String> map = new HashMap<>();

    map.put("John Doe", "555-869-759");
    map.put("Thomas Cook", "555-906-941");
    map.put("Paul Smith", "555-400-321");

    // Gets the Map collection of values and turn it into the Array of Strings
    String[] values = map.values().toArray(new String[0]);

    System.out.println(Arrays.toString(values));
}</code></pre>
<p><b>Output</b></p>
<pre><code class="language-java">[555-400-321, 555-869-759, 555-906-941]</code></pre>
<h2>Map to Array with element order secured</h2>
<p>We have seen that we can get an array of keys and values of the <code>Map</code> using <code>Map.keySet()</code> and <code>Map.values()</code>. Using both methods we can keep the individual elements in separate arrays and construct a new array of key-value pairs from them.</p>
<p>However we will need to use different <code>Map</code> interface implementation than <code>HashMap</code>. We have to use <code>LinkedHashMap</code> which can secure the order of elements in the order of their insertion into the <code>Map</code> data structure implementation. In this way, we can create two different arrays, one for keys and the second for values, but we can rest assure that the order of elements in individual arrays will be matching their mutual pair in the <code>Map</code>.</p>
<pre><code class="language-java">// Method to convert Map elements to an Array in Java
// However, the core of this method lies in the Map's implementation LinkedHashMap
// which maintains the order of inserted elements in the order of their insertion.
public static void useLinkedHashMapElementOrderForArrayConversion()
{
    final Map<String, String> map = new LinkedHashMap<>();

    map.put("John Doe", "555-869-759");
    map.put("Thomas Cook", "555-906-941");
    map.put("Paul Smith", "555-400-321");

    // Get an array of keys in order of the LinkedHashMap
    final String[] keys = map.keySet().toArray(new String[0]);

    // Get an array of values in order of the LinkedHashMap
    final String[] values = map.values().toArray(new String[0]);

    for (int i = 0; i < map.size(); i++) {
        System.out.println( "[ " + keys[i] + " = " + values[i] + " ]" );
    }
}</code></pre>
<p><b>Output</b></p>
<pre><code class="language-java">[ John Doe = 555-869-759 ]
[ Thomas Cook = 555-906-941 ]
[ Paul Smith = 555-400-321 ]</code></pre>
<h2>Map to Array with element order unsecured</h2>
<p>Finally, we need to discuss the option when the elements' order is not secured, but we want to use two different arrays for help.</p>
<p>When we look on the algorithm above, it seems a little bit straightforward how to map elements to an array. However, when <code>HashMap</code> or <code>TreeMap</code> implementation of <code>Map</code> is used, the order of element in both arrays might change. For example for any index <code>i</code>, there is no guarantee that <code>key[i]</code> will represents the pairing key for <code>value[i]</code> value. To guarantee the correct pair position we need to construct helping arrays and map the pair position into the same indexes in helping arrays.</p>
<pre><code class="language-java">// Method to convert Map to an Array in Java
public static void maintainKeySetAndValueCollectionArray()
{
    final Map<String, String> map = new HashMap<>();

    map.put("John Doe", "555-869-759");
    map.put("Thomas Cook", "555-906-941");
    map.put("Paul Smith", "555-400-321");

    // Temporary array to store map keys
    final String[] keys = new String[map.size()];

    // Temporary array to store map values
    final String[] values = new String[map.size()];

    int i = 0;

    for (Map.Entry<String, String> entry : map.entrySet()) {
        keys[i] = entry.getKey();
        values[i] = entry.getValue();
        i++;
    }

    for (i = 0; i < map.size(); i++) {
        System.out.println( "[ " + keys[i] + " = " + values[i] + " ]" );
    }
}</code></pre>
<p><b>Note</b></p>
<p><code>i</code> is local variable. We can insert <code>i</code> incrementation into the <code>values[i]</code> if you like concise code. However for more readable code, we recomment the incrementation to place on to the new line.</p>
<p>Also, local <code>i</code> variable is reseted for <code>System.out</code> line printing.</p>
<p><b>Output</b></p>
<pre><code class="language-java">[ Paul Smith = 555-400-321 ]
[ John Doe = 555-869-759 ]
[ Thomas Cook = 555-906-941 ]</code></pre>
<h2>Conclusion</h2>
<p>This article has shown how to convert Java's <code>Map</code> to an Array by various approaches.</p>
<p>All algorithms are placed in the Java method for quick copy and paste into your projects.</p>
<p>While the first three algorithms (Entry<K,V>, Keys, Values) will cover most of the real-life scenarios of <code>Map</code> to <code>Array</code> conversion, we have shown two more approaches which give you a space for more transformation and conversion. Plus, last two approaches (Map element order secured, Map element order unsecured) pointing out solutions for element order <code>Map</code> security issues.</p>
<p>As always, you can find all our examples on our <a href="https://github.com/codekopf/tutorials-jvm/tree/master/java-basics/java-core/" title="Tutorial JVM - Java Basics - Java Core" target="_blank" rel="nofollow noopener">GitHub project</a>!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/how-to-convert-a-map-to-an-array-in-java/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
