<?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>array &#8211; CodePills.com</title>
	<atom:link href="https://codepills.com/tag/array/feed/" rel="self" type="application/rss+xml" />
	<link>https://codepills.com</link>
	<description>Helping you make a better code</description>
	<lastBuildDate>Tue, 05 Oct 2021 05:10:05 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	
	<item>
		<title>How to calculate median from an array in Java</title>
		<link>https://codepills.com/how-to-calculate-median-from-an-array-in-java/</link>
					<comments>https://codepills.com/how-to-calculate-median-from-an-array-in-java/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Fri, 01 Oct 2021 10:13:54 +0000</pubDate>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[bubble sort]]></category>
		<category><![CDATA[mean]]></category>
		<category><![CDATA[median]]></category>
		<category><![CDATA[quicksort]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1251</guid>

					<description><![CDATA[In this short article, we will see how to compute median in Java. <a href="https://codepills.com/how-to-calculate-median-from-an-array-in-java/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>In this short article, we will see how to compute median in Java.</p>
<p><span id="more-1251"></span></p>
<ul>
<li><a href="#what_is_median">What is median?</a></li>
<li><a href="#difference_between_median_and_mean">What is the difference between the median and mean?</a></li>
<li><a href="#algorithm">Calculate median with simple algorithm</a></li>
<li><a href="#conclusion">Conclusion</a></li>
</ul>
<h2 id="what_is_median">What is median?</h2>
<p>First of all, let&#8217;s get a good idea what <strong>median</strong> actually is. Let&#8217;s look at wiki definition:</p>
<blockquote><p>The median of a list of numbers can be found by first sorting the numbers ascending. If there is an odd number of values, the middle one is picked. If there is an even number of values, the median is then defined to be the average of the two middle values. (Wikipedia)</p></blockquote>
<p>So when we take the definition of median, we need to find the middle in the sorted array.</p>
<h2 id="difference_between_median_and_mean">What is the difference between the median and mean?</h2>
<p>The essential difference is that <strong>the mean</strong> gives a rough average (sum all elements together and divide the sum by the number of elements in the collection) of the whole dataset. At the same time, <stron>the median</stron> will provide the exact centric value, which falls between the smallest and highest value.</p>
<p>It is important to note that a single centric value can be picked only from ordered values arranged in an ascending or descending order for the median.</p>
<p>For example, if I have an array <code>[1,2,3,4,5]</code>, number 3 is the median. But if have an arrray <code>[1,2,3,4,5,6]</code>, number 3.5 is the median.</p>
<h2 id="algorithm">Calculate median with simple algorithm</h2>
<p>Let&#8217;s use few words to describe our algorithm for computing <strong>the median</strong>.</p>
<p>First, we will need to take input. The inputs are the <code>int</code> numbers in the array and the size of the collection. One crucial thing to remember is to <strong>always keep in mind that the values in an array need to be sorted for computing median</strong> Order, ascending or descending, is necessary because we are looking for the value in the centre of the array.</p>
<p>Sorting array happens before computing median, and it is not part of the algorithm for computing median. Therefore, you can use any known sorting algorithm such as quicksort, bubble sort etc.</p>
<p>After taking the inputs, we must first check whether <strong>the number of elements in the array is odd or even</strong>.</p>
<p><u>If the number of elements in the array is even</u>, we compute the median by taking two central pieces and divide them by two.</p>
<p>As we are familiar with arrays in computer science, array order starts with zero and ends with the number of elements minus one. Therefore, when an array length is an even number, we must select the middle array element and element before it.</p>
<p>Eventually, for computing the median for even array length, a division with a number represented as a double value will secure that median with decimal points. Otherwise, division with the number represented as int will floor the number, and the median will be incorrect.</p>
<p>Otherwise, <u>if the number of elements in the array is odd</u>, we compute the median by taking the centric array element.</p>
<p>But, again, as we are familiar with arrays in computer science, array order starts with zero and ends with the number of elements minus one.</p>
<p>We will do a small trick, which can look unnatural at first sight. We add one to the number of array elements in the array of odd length, then divide it by two. And then, we subtract from division one. The resulting number will give us the index position of the central component of the array of odd lengths.</p>
<pre><code class="language-java">public class Median {
    public static void main(String arg[]) {
        int oddLength = 5;
        int oddArr[] = new int[oddLength];
        oddArr[0] = 10;
        oddArr[1] = 30;
        oddArr[2] = 50;
        oddArr[3] = 70;
        oddArr[4] = 90;

        System.out.println("Median for odd length array is : " + computeMedian(oddArr, oddLength);
    
        int evenLength = 6;
        int evenArr[] = new int[evenLength];
        evenArr[0] = 10;
        evenArr[1] = 30;
        evenArr[2] = 50;
        evenArr[3] = 70;
        evenArr[4] = 90;
        evenArr[5] = 100;
    
        System.out.println("Median for even length array is :" + computeMedian(evenArr, evenLength);
    }
    
    private static double computeMedian(int[] arr, int n) {
        if (n % 2 == 0) {
            return (arr[n/2 - 1] + arr[n/2]) / 2.0;
        } else  {
            return arr[(n+1)/2 - 1];
        }
    }
}</code></pre>
<p><b>Output</b></p>
<pre><code class="language-bash">Median for odd length array is : 50
Median for even length array is : 60</code></pre>
<h2 id="conclusion">Conclusion</h2>
<p>This article has shown us a simple algorithm for how to compute median in Java.</p>
<p>It is important to remember that we can compute the median only on sorted arrays. Ascending or descending order does not matter unless we are looking for the value in the centre of the array.</p>
<p>Sorting of the array can happen before computing the median, and you can use any known sorting algorithm.</p>
<p>Did you find computing median easy? Do you have your trick or know another way <u>how to calculate median in Java</u>? Let us know in the comments below the article. We would like to hear your ideas and stories.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/how-to-calculate-median-from-an-array-in-java/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<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 initialize an array with zero values in Java</title>
		<link>https://codepills.com/how-to-initialize-an-array-with-zero-values-in-java/</link>
					<comments>https://codepills.com/how-to-initialize-an-array-with-zero-values-in-java/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Mon, 01 Mar 2021 19:56:37 +0000</pubDate>
				<category><![CDATA[Language basics]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[primitive type]]></category>
		<category><![CDATA[reference type]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1136</guid>

					<description><![CDATA[This article will look at how to fill up Java array with default values effectively on an array creation. <a href="https://codepills.com/how-to-initialize-an-array-with-zero-values-in-java/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>This article will look at how to fill up a Java array with default values effectively on an array creation.</p>
<p><span id="more-1136"></span></p>
<h2>Overview</h2>
<p>Arrays are essential cornerstones of every modern programming language. On a specific occasion, you need to initialize an array with zero values. This article will take you through the pros and cons of the various way how to initialize Java array with default zero values.</p>
<h2>Introduction to Java data types</h2>
<p>In Java we have several different data types. Majority of data types are called primitive data types. To this group belong <strong>byte</strong>, <strong>short</strong>, <strong>int</strong>, <strong>long</strong>, <strong>float</strong>, <strong>double</strong>, <strong>boolean</strong> and <strong>char</strong>.</p>
<p>For more information about Java&#8217;s data type, please read our article about primitive data types.</p>
<p>Speaking about Java&#8217;s data type, there is also a general notation of different data type represented by referencing the object&#8217;s type. We are talking about object references, where the type of the object is classified by the object&#8217;s referencing type. Sound confusing? If you are new to Java, let me point you out to one of the most asked Java questions Is Java pass by value or pass by reference?</p>
<h2>Java data type default values</h2>
<p>Let&#8217;s take a look what is initial (default) value in <strong>Java language</strong> for any variable initialization.</p>
<ul>
<li>The default value for type <strong>byte</strong> is zero. That means in byte the value of (byte) is <strong>0</strong>.</li>
<li>The default value for type <strong>short</strong> is zero. That means in the short the value of (short) is <strong>0</strong>.</li>
<li>The default value for type <strong>int</strong> is zero. That means in int the value of (int) is <strong>0</strong>.</li>
<li>The default value for type <strong>long</strong> is zero. That means in long the value of (long) is <strong>0L</strong>.</li>
<li>The default value for type <strong>float</strong> is positive zero. That means in float the value of (float) is <strong>0.0f</strong>.</li>
<li>The default value for type <strong>double</strong> is positive zero. That means in double the value of (double) is <strong>0.0d</strong>.</li>
<li>The default value for type <strong>boolean</strong> is <strong>false</strong>.</li>
<li>The default value for type <strong>char</strong> is the null character. That means in char the value of (char) is <strong>&#8216;\u0000&#8217;</strong>.</li>
<li>The default value for <strong>all reference</strong> types (Sting or any Object parent or its child) is <strong>null</strong>.</li>
</ul>
<p>If you have noticed, primitive data types are initialized in their form of number zero. The exception is boolean, where the default state is false. However, this representation of the default state comes from generation-lasting philosophical discussion beyond this blog&#8217;s scope.</p>
<h2>Default data type for String and arrays</h2>
<p>It is important to remember that in Java, an array is a container object that holds a fixed number of values of a single type.</p>
<p>The <i>String</i> object is unique in a certain way. It is because it is wrapping object around an array collection of primitive char data types. However, we always reference the <i>String</i> object, not <i>String</i>&#8216;s internal array.</p>
<p><strong>Array of primitive types</strong> keeps initialization value equal default value for each element of primitive data type.</p>
<pre><code class="language-java">double[] treePrimitiveDoubles = new double[3];

double zeroElementPrimitive = treePrimitiveDoubles[0];
System.out.print(zeroElementPrimitive);</code></pre>
<p><b>Output</b></p>
<pre><code class="language-bash">>> 0.0</code></pre>
<p><strong>Array of reference type</strong> keeps initialization value equal null. The <i>String</i> is the same; it keeps the initialization value equal null.</p>
<pre><code class="language-java">Double[] treeReferenceDoubles = new Double[3];

Double zeroElementReference = treeReferenceDoubles[0];
System.out.print(zeroElementReference);</code></pre>
<p><b>Output</b></p>
<pre><code class="language-bash">>> null</code></pre>
<p>We instantly see that we need to create the objects to fill the arrays of the reference type array.</p>
<h2>Filling default values to reference type arrays</h2>
<p>There are two different approaches for reference type arrays on how to fill up an array by a particular type. First is the classic iterative approach, where you loop through the collection and fill the position individually.</p>
<pre><code class="language-java">BankAccount[] arrayOfAllBankAccounts = new BankAccount[50];

for(int i = 0; i < arrayOfAllBankAccounts.length; i++) {
    arrayOfAllBankAccounts[i] = new BankAccount();
}</code></pre>
<p>The second option is to use a more procedural approach with the help of <code>java.util.Arrays</code>. If you want to initialize a one-dimensional array with default values, you can use the static <code>.fill()</code> method. Although, internally <code>.fill()</code> method uses a loop. However, code notation is much more concise. Let's look at the code notation:</p>
<pre><code class="language-java">BankAccount[] arrayOfAllBankAccounts = new BankAccount[50];

Arrays.fill(arrayOfAllBankAccounts, new BankAccount());</code></pre>
<h2>Performance</h2>
<p>Consider the array of arbitrary length which will store reference type for Object counterparts of primitive types such as <strong>Byte</strong>, <strong>Short</strong>, <strong>Integer</strong>, <strong>Long</strong>, <strong>Float</strong>, <strong>Double</strong>, <strong>Boolean</strong> and <strong>Char</strong> class. And imagine now that you would do this for many many arrays like this in your program. This would dramatically decrease performance of your application; you would waste a lot of machine cycles just for initialization. It would affect your application performance by considerable level.</p>
<p>Each array consisted of an Object version of primitive types that would not only take longer to initialize than a regular primitive type array, but it would even require allocating more memory than necessary. Consequently, if you want to use <i>Object</i> version of a primitive type, use them only when essential for your code solution.</p>
<p>Initialization of arrays with primitive types is quick and fast, does not allocate a lot of memory. You can prefer them over their reference type versions.</p>
<h3>String performance</h3>
<p>Java's <i>String</i> class has a special place in our hearts. As we said, <i>String</i> class uses an array of primitive characters for storing text. On each addition or change text, <i>String</i> needs to compute if the allocated array length is sufficient. If it is not, it needs to allocate a new - more significant size for the internal array of primitive characters and copy the existing text to a new array of primitive characters. Resizing mechanism naturally decrease performance. There are two ways how to mitigate this issue. First, it is highly recommended to not use concatenation on <i>String</i>s in your code. And second, if you know you will be using a lot of text manipulation, use the <i>StringBuilder</i> class.</p>
<h2>Conclusion</h2>
<p>In this article, we have seen how to initialize the array in Java with zero values. As always, you can find all codes in this article in out <a href="https://github.com/codekopf/tutorials-jvm/tree/master/java-basics/java-core" title="Tutorial JVM - Java Core" target="_blank" rel="nofollow noopener">GitHub repository</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/how-to-initialize-an-array-with-zero-values-in-java/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
