<?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>streams &#8211; CodePills.com</title>
	<atom:link href="https://codepills.com/tag/streams/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 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>
