<?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>Java 8 &#8211; CodePills.com</title>
	<atom:link href="https://codepills.com/tag/java-8/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>7 different ways how to get NumberFormatException in Java</title>
		<link>https://codepills.com/7-different-ways-how-to-get-numberformatexception-in-java/</link>
					<comments>https://codepills.com/7-different-ways-how-to-get-numberformatexception-in-java/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Thu, 05 May 2022 11:30:51 +0000</pubDate>
				<category><![CDATA[Language basics]]></category>
		<category><![CDATA[exception]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java 8]]></category>
		<category><![CDATA[NumberFormatException]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1304</guid>

					<description><![CDATA[This article will show you the NumberFormatException, how you are getting it and what you should do to handle the exception properly. <a href="https://codepills.com/7-different-ways-how-to-get-numberformatexception-in-java/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>If you get NumberFormatException in Java, it is highly probable because of the following reasons. This article will uncover the NumberFormatException, how you are getting it and what you should do to handle the exception properly.</p>
<p><span id="more-1304"></span></p>
<h2>What is NumberFormatException</h2>
<p>The NumberFormatException is an unchecked Java exception which happens when there is incorrect string input converted to a numeric value. When the input is wrong, NumberFormatException is thrown to inform the user that the conversion requires a correct input and the transformation did not happen. For example, the NumberFormatException is thrown when a numerical string is parsed to an integer, but the string contains also space.</p>
<p>As the NumberFormatException is an unchecked exception, it does not need to be declared in the throws clause of a method or constructor. However, when in doubt of input correctness, it should be handled in code using a try-catch block.</p>
<h2>NumberFormatException Example</h2>
<p>Let&#8217;s take a look at the simple example of NumberFormatException being thrown:</p>
<pre><code class="language-java">public class NumberFormatExceptionExample {
    public static void main(String args[]) {
        int orderNumber = Integer.parseInt("Order 66");
        System.out.println(orderNumber);
    }
}</code></pre>
<p>The above code will throw NumberFormatException. While pure input of string &#8220;66&#8221; is a valid input, a string with non-numerical characters like &#8220;Order 66&#8221; is unsuitable for creating a number.</p>
<pre><code class="language-java">Exception in thread "main" java.lang.NumberFormatException: For input string: "Order 66"
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.base/java.lang.Integer.parseInt(Integer.java:652)
	at java.base/java.lang.Integer.parseInt(Integer.java:770)
    at NumberFormatExceptionExample.main(NumberFormatExceptionExample.java:6)</code></pre>
<h2>8 Different Ways How To Get NumberFormatException</h2>
<p>There are various causes for throwing NumberFormatException, and the improper conversion of invalid input mainly causes them. Here is a list of different ways how to get NumberFormatException:</p>
<p>1. Input string is empty:</p>
<pre><code class="language-java">Integer.parseInt("");</code></pre>
<p>2. Input string is null:</p>
<pre><code class="language-java">Integer.parseInt(null);</code></pre>
<p>3. Input string with non-numeric data:</p>
<p>This case has several different options why it can happen.</p>
<p>a. Input string contains space character:</p>
<pre><code class="language-java">Integer.parseInt("66 66");</code></pre>
<p>b. Input string contains non-numeric character:</p>
<pre><code class="language-java">Integer.parseInt("Sixty");</code></pre>
<p>c. Numeric input with non-numeric character in input string</p>
<pre><code class="language-java">Integer.parseInt("Catch22");</code></pre>
<p>4. Input string with inappropriate symbols in it:</p>
<pre><code class="language-java">Double.parseDouble("66,12345");</code></pre>
<p>5. Input string with leading or tailing white space</p>
<pre><code class="language-java">Integer randomExample = new Integer("  12345  ");</code></pre>
<p><em>Integer</em>, <em>Long</em>, <em>Short</em>, <em>Byte</em> throw NumberFormatException; <em>Double</em>, <em>Float</em> does not.</p>
<p>6. Mismatch of data type between input string and the target data type</p>
<pre><code class="language-java">Integer.parseInt("12.34");</code></pre>
<p>7. Input string exceeding the range of the target data type</p>
<pre><code class="language-java">Integer.parseInt("2147483648");</code></pre>
<p>The example shown above is a case of NumberFormatException upon placing a numeric input string exceeding the range of the target data type, which is in our case <em>Integer</em> class object. The maximum range for Integer class object is from -2_147_483_648 to 2_147_483_647.</p>
<h2>How to handle NumberFormatException</h2>
<p>The NumberFormatException is an unchecked exception in Java. Therefore it can be handled as any other Java exception by wrapping critical code to try-catch block.</p>
<p>Look at the following example of catching NumberFormatException with a try-catch block:</p>
<pre><code class="language-java">public class NumberFormatExceptionExample {

    public static void main(String args[]) {
        String userInput = "Order 66";
        Optional&lt;Integer&gt; orderNumber = processOrder(userInput);
        if (orderNumber.isPresent()) {
            System.out.println("Execute order " + orderNumber.get());
        } else {
            System.out.println("Unrecognized order number. Please try again.");
        }
    }

    public static Optional&lt;Integer&gt; processOrder(String userInput) {
        try {
            int order = Integer.parseInt(userInput);
            return Optional.of(order);
        } catch (NumberFormatException ex) {
            System.out.println("Order exception: Invalid user input!");
        }
        return Optional.empty();
    }

}</code></pre>
<p>Depending on the requirements of the application, take necessary action. For example, log the exception with an appropriate message or return an empty Optional object if you are using at least Java 8. Like in the example above, wrapping the code in try-catch blocks allows the program to continue execution after the code throws the exception.</p>
<p><b>Output</b>:</p>
<pre><code class="language-bash">Order exception: Invalid user input!
Unrecognized order number. Please try again.</code></pre>
<h2>Conclusion</h2>
<p>This article led us to explain what NumberFormatException and how to handle it. It also showed over seven different ways how the NumberFormatException can occur and how we can defensively take care of it.</p>
<p>Do you know NumberFormatException? In what case did it throw to you? Do you have your trick, or do you see another way <u>how to handle NumberFormatException</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/7-different-ways-how-to-get-numberformatexception-in-java/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Developer Notes 001</title>
		<link>https://codepills.com/developer-notes-001/</link>
					<comments>https://codepills.com/developer-notes-001/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Sun, 01 May 2022 13:34:28 +0000</pubDate>
				<category><![CDATA[Tips & tricks]]></category>
		<category><![CDATA[curl]]></category>
		<category><![CDATA[Enum]]></category>
		<category><![CDATA[interpunct]]></category>
		<category><![CDATA[Jackson]]></category>
		<category><![CDATA[Java 8]]></category>
		<category><![CDATA[Lombok]]></category>
		<category><![CDATA[NUMBER]]></category>
		<category><![CDATA[Oracle DB]]></category>
		<category><![CDATA[Postman]]></category>
		<category><![CDATA[serialization]]></category>
		<category><![CDATA[String]]></category>
		<category><![CDATA[Switch]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1298</guid>

					<description><![CDATA[The list of a few developer notes collected during the software development which were not enough for a self-standing article. <a href="https://codepills.com/developer-notes-001/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>This article selects a few developer notes collected during the software development, which were unfortunately not enough for a self-standing article.</p>
<p><span id="more-1298"></span></p>
<p>Developer notes will be an irregular series of articles where I will briefly go through some of my notes to make notes for posterity. The notes themself can be pretty long, yet their length is not enough for writing a meaningful article.</p>
<p>Let&#8217;s take a look at a list of content:</p>
<ul>
<li><a href="#oracle_error" title="Oracle Error: Value Larger Than Specified Precision Allowed For This Column">Oracle Error: Value Larger Than Specified Precision Allowed For This Column</a></li>
<li><a href="#switch_on_string_with_enum_name_in_java_8" title="Switch on String in Java">Switch on String with Enum Name in Java 8</a></li>
<li><a href="#lomboks_serialization_error_for_jackson" title="Lombok's serialization error for Jackson">Lombok&#8217;s serialization error for Jackson</a></li>
<li><a href="#interpunct" title="Interpunct">Interpunct</a></li>
<li><a href="#how_to_do_curl_in_postman" title="How To Do CURL in Postman">How To Do <em>curl</em> in Postman</a></li>
</ul>
<h2 id="oracle_error">Oracle Error: Value Larger Than Specified Precision Allowed For This Column</h2>
<p>I was getting errors on inserting data into the Oracle database &#8220;ORA-01438: value larger than specified precision allowed for this column.&#8221;</p>
<p>The reason why I was getting an error was a too big number. When I looked over UI to database column definition, I saw something like this NUMBER(15,2).</p>
<p>Official Oracle documentation, as for <a href="https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/Data-Types.html#GUID-75209AF6-476D-4C44-A5DC-5FA70D701B78" title="Number datatype" target="_blank" rel="nofollow noopener">Oracle database v21</a>, depicts <code>NUMBER</code> datatype defined as <code>NUMBER (precision,scale)</code>.</p>
<p><code>NUMBER</code> datatype notation can be rather rewritten to <i>NUMBER (size,precision)</i>) where the first number depicts the total size of the digits in a number, and the second means the decimal point scale.</p>
<p>In other words, for example, for <code>NUMBER(2,2)</code>, we can place the column number consisting of 2 digits, both of which will be decimals. i.e. 0.15, 0.45 etc. But if we would like to have a bigger number in the column, we need to upgrade the size of the column reserved for the whole number &#8211; <code>NUMBER(5,2)</code> will get us five digits, of which 2 are decimals. i.e 125.40, 18.00.</p>
<h2 id="switch_on_string_with_enum_name_in_java_8">Switch on String with Enum Name in Java 8</h2>
<p>Here is an example of how to use <em>Enum</em> values as strings in a <code>switch</code> case. You can only use the strings which are known at compile time. The compiler cannot determine the result of expression. However, in Java <em>Enum</em> case <code>VALUE1, VALUE2</code> are static.</p>
<pre><code class="language-java">String name = ...
switch(CustomEnum.valueOf(name)) {
   case VALUE1:
        ...
        break;
   case VALUE2:
        ...
        break;
    ...
}</code></pre>
<h2 id="lomboks_serialization_error_for_jackson">Lombok&#8217;s serialization error for Jackson</h2>
<p>When I created a new aggregated DTO class on my REST output, I got the following error:</p>
<pre><code class="language-bash">Type definition error: [simple type, class CUSTOM_DTO_CLASS_NAME]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class CUSTOM_DTO_CLASS_NAME and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: CUSTOM_DTO_CLASS_NAME[\"aggregation-class-property\"]->java.util.ArrayList[0])</code></pre>
<p>I am sure this error will be thrown quiet often as the solution on it is very simple. All I was missing on my <i>Custom DTO</i> class was <strong>Lombok&#8217;s</strong> <code>@Getters</code> annotation for serialization. So fix consisted on adding missing <code>@Getters</code> annotation on the top of my custom class for Lombok generating getter methods at compile time.</p>
<h2 id="interpunct">Interpunct</h2>
<p>I was editing my resume this month and wanted to create a nice date range in positions I held in the past. I got this from my LinkedIn profile, where LinkedIn use dates in the form as <em>Jan 2020 – Feb 2020 · 2 mos</em>. But I could not figure out where to take the dot sign as it was an image. However, the character for such sign as little black dot <strong>·</strong> really exists and its name is <strong>Interpunct</strong>,  or <strong>middle dot</strong>. So every time you would like to create a nice division of text with the help of <strong>·</strong>, think about the <strong>Interpunct</strong>.</p>
<h2 id="how_to_do_curl_in_postman">How To Do <em>curl</em> in Postman</h2>
<p>Is there a way hot to make a <em>curl</em> command in Postman? What if we would like to import the <em>curl</em> command easily into Postman and make a Postman GUI request from it.<br />
Is it even possible to easily translate all the <em>curl</em> command parameters into the Postman request?</p>
<p>Surely it is. Postman request are eventually nothing else than more fancy <em>curl</em> requests and Postman supports the <em>curl</em> import feature. Importing <em>curl</em> is very simple. Here is simple list of steps which will lead you to success:</p>
<ol>
<li>Open Postman.</li>
<li>Go to navigation menu, click File and Import option</li>
<li>In <i>Import</i> window select the raw text tab.</li>
<li>Paste the raw text e.g. <code>curl --location --request GET "https://www.google.com/"</code>, then click continue.</li>
<li>Check the name, format and import as.</li>
<li>If everything is correct, click <i>Import</i> button.</li>
</ol>
<p>Following the steps will automatically import the <em>curl</em> command into the Postman on the new tab.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/developer-notes-001/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Flattening Stream Collections in Java</title>
		<link>https://codepills.com/flattening-stream-collections-in-java/</link>
					<comments>https://codepills.com/flattening-stream-collections-in-java/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Tue, 01 Mar 2022 15:24:06 +0000</pubDate>
				<category><![CDATA[Language basics]]></category>
		<category><![CDATA[collections]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java 8]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1289</guid>

					<description><![CDATA[This article is about flattening the list of element list with use of Java 8 stream feature <em>flatMap</em> and <em>forEach</em> <a href="https://codepills.com/flattening-stream-collections-in-java/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>This article is about Java 8 stream feature <em>flatMap</em>. If we have a <code>List&lt;List&lt;Object&gt;&gt;</code>, how can we turn the list of lists into a single list that contains all the elements from the lists in the same streamflow using the features of Java 8?</p>
<p><span id="more-1289"></span></p>
<h2>Introduction</h2>
<p>The answer is simply to use <em>flatMap</em> to flatten the lists of elements into one coherent list of the same elements. <code>flatMap</code> converts lists to streams in a single Stream and then collects the result into a list.</p>
<p>The best explanation will probably show the example of <em>flatMap</em> in action.</p>
<h2>Flattening the List with <em>flatMap</em> &#8211; Simple Example</h2>
<p>Let&#8217;s start with a simple example and continue with a more complex case later in the article. Our simple example will have a list of list with <em>String</em> elements. Each inner list contains a list of <em>String</em> elements which is a tuplet denoting at the first position the level of list and in the second position the overall total position of <em>String</em> element.</p>
<pre><code class="language-java">List&lt;List&lt;String&gt;&gt; nestedList = asList(
    asList("1-1", "1-2", "1-3"),
    asList("2-4", "2-5", "2-6", "2-7", "2-8"),
    asList("3-9", "3-10")
);</code></pre>
<p>We take this simple list above, and we will push it to our simple flattening method <em>flatteningTheListOfLists(List&lt;List&lt;String&gt;&gt; list)</em>.</p>
<pre><code class="language-java">public  List&lt;String&gt; flattenListOfLists(List&lt;List&lt;String&gt;&gt; list) {
    return list.stream()
               .flatMap(Collection::stream)
               .collect(Collectors.toList());
}</code></pre>
<p>As a result, we will get a list with all the <em>String</em> elements in one list.</p>
<pre><code class="language-java">@Test
public void testFlatteningTheListOfLists_simpleScenario() {
     List&lt;String&gt; flattenedList = flattenListOfLists(nestedList);

    assertNotNull(flattenedList);
    assertEquals(10, flattenedList.size());

    for (String element : flattenedList) {
        System.out.print(element);
    }
}</code></pre>
<p><b>Output</b></p>
<pre><code class="language-bash">1-1, 1-2, 1-3, 2-4, 2-5, 2-6, 2-7, 2-8, 3-9, 3-10, </code></pre>
<h2>Flattening the List with <em>flatMap</em> &#8211; Realistic Scenario</h2>
<p>Instead of a simple play with a happy case scenario, hypothetically, let&#8217;s have a more advanced system where we will generate the list of objects directly in the stream. We will have a list of employees with their job position. And we would like to collect all their possible career options for employees above <i>junior engineer</i> level into a single list of all career options across all employees through a department. The resulting list will give us a list of possible combinations of employee promotions above the junior level.</p>
<p>Here is an example of <em>Employee</em> class:</p>
<pre><code class="language-java">public class Employee {

    private Position position;

    public Employee(Position position) {
        this.position = position;
    }

    public int getPosition() {
        return this.position;
    }
}</code></pre>
<p>And here is an example of <em>Employee</em> and <em>Position</em> class:</p>
<pre><code class="language-java">public class Employee {

    private final String name;
    private final Position position;

    public Employee(String name, Position position) {
        this.name = name;
        this.position = position;
    }

    public Position getPosition() {
        return position;
    }

}</code></pre>
<pre><code class="language-java">public enum Position {

    JUNIOR_ENGINEER(1),
    SENIOR_ENGINEER(2),
    SOFTWARE_ARCHITECT(3),
    ENGINEERING_MANAGER(4);

    private final int level;

    Position(int level) {
        this.level = level;
    }

    public int getLevel() {
        return this.level;
    }
}</code></pre>
<p>In order to get the list of all possible career options for all employees above <i>junior level</i> we would create for example something like <code>getAllCareerOptionsAboveJunior(List&lt;Employee&gt; employees)</code> where class <em>employee</em> property is a list of employees of <em>Employee</em> class. <code>getAllCareerOptionsAboveJunior(List&lt;Employee&gt; employees)</code> method will go through all the employees, filter employees from the list with level above junior level and create a list of possible career options for that specific employee. All the career options should be than pushed to <code>List</code> and outputted from stream to <code>List</code> collector.</p>
<pre><code class="language-java">public List&lt;Position&gt; getAllCareerOptionsAboveJunior(List&lt;Employee&gt; employees) {
    return employees.stream()
                    .filter(employee -> employee.getPosition().getLevel() > Position.JUNIOR_ENGINEER.getLevel())
                    .map(employee -> createPossibleCareerOptions(employee.getPosition().getLevel())) // This is bad practice and will not work
                    .collect(Collectors.toList());
}</code></pre>
<p>Example of <i>createPossibleCareerOptions()</i>:</p>
<pre><code class="language-java">public List&lt;Position&gt; createPossibleCareerOptions(int level) {
    return Arrays.stream(Position.values())
                 .filter(position -> position.getLevel() > level)
                 .collect(Collectors.toList());
}</code></pre>
<p>As we can see above, we mapped an employee to the list of her/his career options. But we want to collect list of all possibilities, not list of lists. Therefore, the code above does not work while stream <code>map</code> function maps <code>employee</code> instance into the list, but stream collector can not collect list of position list into the single list.</p>
<p>To make this code work, we need to introduce a consequent function in a stream that will flatten the list&#8217;s mapping into one stream. We need to place <code>flatMap</code> function for flattening the stream of list of positions into single steam positions for our Java stream.</p>
<pre><code class="language-java">public List&lt;Position&gt; getAllCareerOptionsAboveJunior(List&lt;Employee&gt; employees) {
    return employees.stream()
                    .filter(employee -> employee.getPosition().getLevel() > Position.JUNIOR_ENGINEER.getLevel())
                    .map(employee -> createPossibleCareerOptions(employee.getPosition().getLevel()))
                    .flatMap(List::stream) // I need to flatten list streams into one stream
                    .collect(Collectors.toList());
}</code></pre>
<p>Finally, let&#8217;s put all parts together and try the solution on the list of employees.</p>
<pre><code class="language-java">List&lt;Employee&gt; employees = asList(
        new Employee("Mark", Position.JUNIOR_ENGINEER),
        new Employee("Thomas", Position.SENIOR_ENGINEER),
        new Employee("Janet", Position.SOFTWARE_ARCHITECT),
        new Employee("Percy", Position.ENGINEERING_MANAGER)
);</code></pre>
<p>We can test the result with the test written below:</p>
<pre><code class="language-java">@Test
public void testFlatteningTheListOfLists_realisticScenario() {
    List&lt;Position&gt; allPossiblePromotions = getAllCareerOptionsAboveJunior(employees);

    assertNotNull(allPossiblePromotions);
    assertEquals(3, allPossiblePromotions.size());

    for (Position position : allPossiblePromotions) {
        System.out.print(position + ", ");
    }
}</code></pre>
<p><b>Output</b></p>
<pre><code class="language-bash">SOFTWARE_ARCHITECT, ENGINEERING_MANAGER, ENGINEERING_MANAGER, </code></pre>
<p><b>Note</b> : If you have better idea for <code>Map</code> sorting, let me know in comments below.</p>
<h2>Flattening the <em>List</em> With <em>forEach</em></h2>
<p>To flatten this nested collection into a list of the same elements, we can also use <em>forEach</em> together with a Java 8 method reference. However, the solution with <em>forEach</em> might be discouraged by some developers as it needs to create a new reference on the list with results before it returns the complete results. Thus, creating the result variable will make the code more cumbersome and brittle. And while it might be suitable for small lists and simple applications, it brings pointlessly more complexity with its wrapping code for more complex scenarios as described above. On the contrary, it provides no advantage in the form of, for example, code readability.</p>
<p>Neither to say, let&#8217;s take a look at the option of flattening the stream of element&#8217;s list with the help of <em>forEach</em> method.</p>
<pre><code class="language-java">public List&lt;String&gt; useOfForEach(Stream&lt;List&lt;String&gt;&gt; streamOfLists) {
    List&lt;String&gt; result = new ArrayList<>();
    streamOfLists.forEach(result::addAll);
    return result;
}</code></pre>
<p>If we use the same list of simple <em>String</em> elements as for happy case scenario with <em>flatMap</em> we will get the same results.</p>
<h2>Conclusion</h2>
<p>We have seen in this article how to use a Java 8 Stream method <em>flatMap</em> first on a simple example and then on a more realistic scenario. We have also seen the option of flattening the stream with <em>forEach</em>. However, use of <em>forEach</em> might be discouraged on more realistic scenario when used on stream of <i>Objects</i> which generates the lists.</p>
<p>Did you find use of <em>flatMap</em> hard? Do you have your trick or you know another way <u>how to use <em>flatMap</em></u>? Let us know in the comments below the article. We would like to hear your ideas and stories.</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/flattening-stream-collections-in-java/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to join List String elements with a comma</title>
		<link>https://codepills.com/how-to-join-list-string-elements-with-a-comma/</link>
					<comments>https://codepills.com/how-to-join-list-string-elements-with-a-comma/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Sat, 01 Jan 2022 14:09:21 +0000</pubDate>
				<category><![CDATA[Language basics]]></category>
		<category><![CDATA[brute force]]></category>
		<category><![CDATA[Java 8]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1277</guid>

					<description><![CDATA[In this article, we will see three different ways to print string elements of the list into one coherent text. <a href="https://codepills.com/how-to-join-list-string-elements-with-a-comma/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>This article will show three different ways to print string elements of the list into one coherent text.</p>
<p><span id="more-1277"></span></p>
<h2>Introduction</h2>
<p>A software developer encounters the trivial task of joining string elements in the list from time to time into one coherent text. Reasons vary widely &#8211; from printing elements to logs to showing the text to the user. But be sure that the solution for this problem should be straightforward when you want to use the Java programming language the most effectively.</p>
<p>We will use a list of random US states codes such as  TX, WA, NY etc., for demonstration in our showcases.</p>
<p>First of all, let me show you the proper way to utilize the Java language most effectively. These solutions will require to use of at least version Java 8.</p>
<h2>String build-in join method</h2>
<p>Java 8 implemented to core String class, in a same way as many other programming languages, <code>join()</code> method. <code>join()</code> method has two arguments:</p>
<ul>
<li>The first argument is called <b>separator</b>. Separator is single character or sequence of characters with which elements should be joined together.</li>
<li>The second argument is the Java&#8217;s object implementing the List interface from which the elements will be taken and joined.</li>
</ul>
<p>Be noted that a separator can be a single character or sequence of characters. We will connect our US state codes on the sequence of characters: space + comma + space. You can use only a comma to get a more concise text.</p>
<pre><code class="language-java">package com.codepills;

import java.util.Arrays;
import java.util.List;

public class JoiningStatesWithJoinMethod {

    public static void main(String[] args) {
        List<String> states = Arrays.asList("TX", "WA", "NY", "AZ", "MI", "AL", "CA");
        String text = String.join(" , ", states);
        System.out.println(text);
    }

}</code></pre>
<p><b>Output</b></p>
<pre><code class="language-java">TX , WA , NY , AZ , MI , AL , CA</code></pre>
<h2>Joining String elements in Java Stream</h2>
<p>Another way to join string elements and create a single line of text is to stream through all the list elements and join them on a collection of characters or sequences of characters. Unfortunately, this solution also requires using at least the Java 8 version since handling and collecting streams is a significant release feature of Java 8. Let&#8217;s use Collector&#8217;s <code>joining()</code> static method with single argument &#8211; separator.</p>
<pre><code class="language-java">package com.codepills;

import java.util.Arrays;
import java.util.List;

public class JoiningStatesWithStreamCollection {

    public static void main(String[] args) {
        List<String> states = Arrays.asList("TX", "WA", "NY", "AZ", "MI", "AL", "CA");
        String text = states.stream().collect(Collectors.joining(","));
        System.out.println(text);
    }

}</code></pre>
<p><b>Output</b></p>
<pre><code class="language-java">TX , WA , NY , AZ , MI , AL , CA</code></pre>
<h2>Brute force</h2>
<p>The last way to join strings together is to use simply brute force. Using brute force is the last option as it creates more code than necessary. Especially for newer versions of Java, it is recommended to use String&#8217;s build-in <code>join()</code> method. Therefore brute-force is more or less an option for legacy code, code written in Java 7 and less.</p>
<pre><code class="language-java">package com.codepills;

import java.util.Arrays;
import java.util.List;

public class JoiningStatesWithBruteForce {

    public static void main(String[] args) {
        System.out.println(customJoin(",", Arrays.asList("TX", "WA", "NY", "AZ", "MI", "AL", "CA")));
        System.out.println(customJoin(",", Arrays.asList("TX")));
        System.out.println(customJoin(",", Arrays.asList("")));
        System.out.println(customJoin(",", null));
    }

    private static String customJoin(String separator, List<String> input) {

        if (input == null || input.size() <= 0) return "";

        StringBuilder stringBuilder = new StringBuilder();

        for (int i = 0; i < input.size(); i++) {
            stringBuilder.append(input.get(i));
            // Do not print separator for the last element
            if (i != input.size() - 1) {
                stringBuilder.append(separator);
            }
        }

        return stringBuilder.toString();
    }

}</code></pre>
<p><b>Output</b></p>
<pre><code class="language-java">TX , WA , NY , AZ , MI , AL , CA
TX
 // empty
</code></pre>
<p>We placed all possible options for input to <code>main()</code> method in order to test our <code>customJoin()</code> method properly.</p>
<p>Eventually, you can see we are using more custom code than is necessary. All this custom functionality can be replaced by single line in case of String's <code>join()</code> method. Therefore use this custom solution only when it does make sense.</p>
<h2>Conclusion</h2>
<p>This article has shown three different ways to print string elements of the list into one coherent test.</p>
<p>Did you find concatenating easy? Do you have your trick or know another way <u>how to join list elements</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-join-list-string-elements-with-a-comma/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>
		<item>
		<title>How to use IntStream range in Java</title>
		<link>https://codepills.com/how-to-use-intstream-range-in-java/</link>
					<comments>https://codepills.com/how-to-use-intstream-range-in-java/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Sun, 06 Dec 2020 11:55:43 +0000</pubDate>
				<category><![CDATA[Language basics]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java 8]]></category>
		<category><![CDATA[range]]></category>
		<category><![CDATA[streams]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1079</guid>

					<description><![CDATA[This article talks about the average use case of loop count variable usage via IntStream API <a href="https://codepills.com/how-to-use-intstream-range-in-java/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>I often encounter a situation where I need to loop through a collection in Java. While looping through the collection sequentially, I usually want to use a temporal loop count variable as a variable with which I will be working inside the loop.</p>
<p><span id="more-1079"></span></p>
<p>Java 8 come with beautiful solution on this pattern. It is called <code>IntStream</code>.</p>
<h2>Example of IntStream range() method</h2>
<p>Static method <code>range(startInclusive, endExclusive)</code> of <code>IntStream</code> class returns a sequential ordered of integer numbers from range of <b>startInclusive (inclusive)</b> to <b>endExclusive (exclusive)</b> by an incremental step of 1. Therefore <i>startInclusive</i> is inclusive initial value and <i>endInclusive</i> is exclusive upper bound.</p>
<p>All this is equivalent of sequence increasing values sequentially using a for loop as follows: <code>for (int i = startInclusive; i < endInclusive ; i++) { ... }</code></p>
<p><b>Example code:</b></p>
<pre><code class="language-java">IntStream intStream = IntStream.range(1, 5);
intStream.forEach(i -> {
    System.out.print(i + " ");
});</code></pre>
<p><b>Example output:</b></p>
<pre><code class="language-bash">1 2 3 4 </code></pre>
<h2>Example of IntStream rangeClosed() method</h2>
<p>Static method <code>rangeClosed(startInclusive, endInclusive)</code> of <code>IntStream</code> class returns a sequential ordered of integer numbers from range of <b>startInclusive (inclusive)</b> to <b>endInclusive (inclusive)</b> by an incremental step of 1. Therefore <i>startInclusive</i> is inclusive initial value and <i>endInclusive</i> is inclusive upper bound.</p>
<p>All this is equivalent of sequence increasing values sequentially using a for loop as follows: <code>for (int i = startInclusive; i <= endInclusive ; i++) { ... }</code></p>
<p><b>Example code:</b></p>
<pre><code class="language-java">IntStream intStream = IntStream.rangeClosed(1, 5);
intStream.forEach(i -> {
    System.out.print(i + ", ");
});</code></pre>
<p><b>Example output:</b></p>
<pre><code class="language-bash">1 2 3 4 5</code></pre>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/how-to-use-intstream-range-in-java/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
