<?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>Map &#8211; CodePills.com</title>
	<atom:link href="https://codepills.com/tag/map/feed/" rel="self" type="application/rss+xml" />
	<link>https://codepills.com</link>
	<description>Helping you make a better code</description>
	<lastBuildDate>Sat, 18 Jun 2022 13:52:58 +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>
		<item>
		<title>How to sort a map with Java 8</title>
		<link>https://codepills.com/how-to-sort-a-map-with-java-8/</link>
					<comments>https://codepills.com/how-to-sort-a-map-with-java-8/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Sat, 06 Mar 2021 13:22:56 +0000</pubDate>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[generics]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java 8]]></category>
		<category><![CDATA[Map]]></category>
		<category><![CDATA[sort]]></category>
		<category><![CDATA[sorting]]></category>
		<category><![CDATA[streams]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1146</guid>

					<description><![CDATA[This tutorial shows how to sort Java Map implementations with Java 8 streams by map's key or value properties. <a href="https://codepills.com/how-to-sort-a-map-with-java-8/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>This tutorial will show how to sort <code>Map</code> implementations with the map&#8217;s key or value properties.</p>
<p><span id="more-1146"></span></p>
<h2>Introduction</h2>
<p>Every approach for sorting a map consists of a few consequent steps, no matter by which map&#8217;s property (key/value)n we want to sort <code>Map</code>.</p>
<h3>Basic sorting algorithm</h3>
<p>Sorting <code>Map</code> algorithm goes like this:</p>
<ul>
<li>First, we convert a <code>Map</code> into a <code>Stream</code></li>
<li>Second, we sort streaming elements</li>
<li>Third, we collect sorted elements, and we maintain order by placing elements into the correct data structure (<code>LinkedHashMap</code>)</li>
</ul>
<h3>HashMap entrySet() method in Java</h3>
<p>The <code>java.util.HashMap.entrySet()</code> method in Java is used to create a set out of the same elements contained in the <code>HashMap</code>. It returns a set of entries from the <code>HashMap</code>. Alternatively we can create a new set and store the map elements into it.</p>
<h2>Sort Map by Keys</h2>
<pre><code class="language-java">public void sortMapByKeys() {

    Map&lt;String, Integer&gt; unsortedMap = new HashMap<>();

    unsortedMap.put("z", 0);
    unsortedMap.put("b", 5);
    unsortedMap.put("a", 6);
    unsortedMap.put("e", 7);
    unsortedMap.put("k", 8);
    unsortedMap.put("f", 9);
    unsortedMap.put("n", 100);
    unsortedMap.put("o", -4);
    unsortedMap.put("m", 2);
    unsortedMap.put("d", 1);

    System.out.println("Unsorted map: ");
    System.out.println(unsortedMap);

    // We need a LinkedHashMap to keep an order of newly returned sorted map.
    Map&lt;String, Integer&gt; result = unsortedMap.entrySet()
        .stream()
        .sorted(Map.Entry.comparingByKey())
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));

    // Alternative way
    Map&lt;String, Integer&gt; resultAlternative = new LinkedHashMap<>();
    unsortedMap.entrySet()
        .stream()
        .sorted(Map.Entry.comparingByKey())
        .forEachOrdered(x -> resultAlternative.put(x.getKey(), x.getValue()));

    System.out.println("Sorted map by keys: ");
    System.out.println(result);
    System.out.println(resultAlternative);
}</code></pre>
<p><b>Output</b></p>
<pre><code class="language-bash">Unsorted map:
{a=6, b=5, d=1, e=7, f=9, z=0, k=8, m=2, n=100, o=-4}

Sorted map by keys:
{a=6, b=5, d=1, e=7, f=9, k=8, m=2, n=100, o=-4, z=0}
{a=6, b=5, d=1, e=7, f=9, k=8, m=2, n=100, o=-4, z=0}</code></pre>
<p>Order in <i>unsortedMap</i> is not secured. However, after the map sorting with the key, we can see that the map is ordered. The newly created map is placed in <code>LinkedHashMap</code> implementation,  which maintains the elements&#8217; order.</p>
<h2>Sort Map by Values</h2>
<pre><code class="language-java">public void sortMapByValues() {

    Map&lt;String, Integer&gt; unsortedMap = new HashMap<>();

    unsortedMap.put("z", 0);
    unsortedMap.put("c", 7);
    unsortedMap.put("q", 4);
    unsortedMap.put("a", 6);
    unsortedMap.put("e", 7);
    unsortedMap.put("k", 8);
    unsortedMap.put("n", 100);
    unsortedMap.put("o", -4);
    unsortedMap.put("m", 2);
    unsortedMap.put("d", 1);

    System.out.println("Unsorted map: ");
    System.out.println(unsortedMap);

    // We need a LinkedHashMap to keep an order of newly returned sorted map.
    Map&lt;String, Integer&gt; result = unsortedMap.entrySet()
        .stream()
        .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));

    // Alternative way
    Map&lt;String, Integer&gt; resultAlternative = new LinkedHashMap<>();
    unsortedMap.entrySet()
        .stream()
        .sorted(Map.Entry.&lt;String, Integer&gt;comparingByValue().reversed())
        .forEachOrdered(x -> resultAlternative.put(x.getKey(), x.getValue()));

    System.out.println("Sorted map by values: ");
    System.out.println(result);

    System.out.println("Sorted map by values (alternative approach): ");
    System.out.println(resultAlternative);
}</code></pre>
<p><b>Output</b></p>
<pre><code class="language-bash">Unsorted map:
{q=4, a=6, c=7, d=1, e=7, z=0, k=8, m=2, n=100, o=-4}

Sorted map by values:
{n=100, k=8, c=7, e=7, a=6, q=4, m=2, d=1, z=0, o=-4}

Sorted map by values (alternative approach):
{n=100, k=8, c=7, e=7, a=6, q=4, m=2, d=1, z=0, o=-4}</code></pre>
<p>Order in <i>unsortedMap</i> is not secured. However, after the map is sorted by value, we can see it is in order. The newly created map is kept in <code>LinkedHashMap</code> implementation, which maintains the elements&#8217; order.</p>
<h2>Sort special case of Map&lt;Object,Object&gt;</h2>
<p>There exist special case in <code>Map</code> sorting. It is when we place <code>Object</code> type into the <code>Map</code> parameters. The Stream can’t sort the <code>Map&lt;Object, Object&gt;</code> directly. To solve this case we need to convert <code>Map&lt;Object, Object></code> into <code>Map&lt;String, String&gt;</code>. Let&#8217;s take a look on the code example below:</p>
<p><b>Note</b> : If you have better idea for <code>Map</code> sorting, let me know in comments below.</p>
<pre><code class="language-java">public void sortObjectMap() {

    // Example of the Object map
    Properties properties = System.getProperties();
    Set&lt;Map.Entry&lt;Object, Object&gt;&gt; entries = properties.entrySet();

    System.out.println("Unsorted Object map: ");
    entries.forEach(System.out::println);

    LinkedHashMap&lt;String, String&gt; collect = entries.stream()
        .collect(Collectors.toMap(k -> (String) k.getKey(), e -> (String) e.getValue()))
        .entrySet()
        .stream()
        .sorted(Map.Entry.comparingByKey())
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));

    System.out.println("Sorted Object map by keys: ");
    result.forEach((key, value) -> System.out.println(key + " : " + value));
}</code></pre>
<p><b>Output</b></p>
<pre><code class="language-bash">Unsorted Object map:
sun.desktop=windows
java.specification.version=8
...

Sorted Object map by keys:
awt.toolkit:sun.awt.windows.WToolkit
file.encoding:UTF-8
file.separator:\
java.awt.graphicsenv:sun.awt.Win32GraphicsEnvironment
...</code></pre>
<h2>Conclusion</h2>
<p>In this article we have shown how to sort <code>Map</code> by key and by value. As some implementation of <code>Map</code> do not maintain order we created ordered maps with <code>LinkedHashMap</code>.</p>
<p>Eventually we have shown a special case of <code>Map&lt;Object, Object&gt;</code> which require transformation of <code>Object</code> into the string in order to to be compared by key or value.</p>
<p>As always, you can find all our examples on our <a href="https://github.com/codekopf/tutorials-jvm/tree/master/java-basics/java8/" title="Tutorial JVM - Java Basics - Java 8" target="_blank" rel="nofollow noopener">GitHub project</a>!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/how-to-sort-a-map-with-java-8/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
