<?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>Guava &#8211; My Shitty Code</title>
	<atom:link href="https://myshittycode.com/tag/guava/feed/" rel="self" type="application/rss+xml" />
	<link>https://myshittycode.com</link>
	<description>Embracing the Messiness in Search of Epic Solutions</description>
	<lastBuildDate>Fri, 06 Jan 2023 16:51:09 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.1</generator>

<image>
	<url>https://myshittycode.com/wp-content/uploads/2022/04/cropped-icon-32x32.png</url>
	<title>Guava &#8211; My Shitty Code</title>
	<link>https://myshittycode.com</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">205304208</site>	<item>
		<title>Groovy + GPars: Handling Concurrency</title>
		<link>https://myshittycode.com/2017/04/06/groovy-gpars-handling-concurrency/</link>
					<comments>https://myshittycode.com/2017/04/06/groovy-gpars-handling-concurrency/#respond</comments>
		
		<dc:creator><![CDATA[Shitty Author]]></dc:creator>
		<pubDate>Fri, 07 Apr 2017 02:37:44 +0000</pubDate>
				<category><![CDATA[Programming Language]]></category>
		<category><![CDATA[GPars]]></category>
		<category><![CDATA[Guava]]></category>
		<guid isPermaLink="false">http://myshittycode.com/?p=939</guid>

					<description><![CDATA[<p>PROBLEM Let&#8217;s assume given a list of user IDs (ex: 1, 2, 3, 4, and 5), we need to query 2 data sources to get the names and the addresses before returning a list of Employee objects. The Employee class looks like this:- We are going to explore multiple solutions to implement lookup(..) to run [&#8230;]</p>
<p>The post <a rel="nofollow" href="https://myshittycode.com/2017/04/06/groovy-gpars-handling-concurrency/">Groovy + GPars: Handling Concurrency</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">PROBLEM</h2>



<p>Let&#8217;s assume given a list of user IDs (ex: 1, 2, 3, 4, and 5), we need to query 2 data sources to get the names and the addresses before returning a list of <code>Employee</code> objects. The <code>Employee</code> class looks like this:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
class App {
    String nameLookup(Integer id) {
        log(&quot;Name lookup: ${id}&quot;)
        Thread.sleep(2000)
        &quot;User ${id}&quot;
    }

    String addressLookup(Integer id) {
        log(&quot;Addr lookup: ${id}&quot;)
        Thread.sleep(4000)
        &quot;Address ${id}&quot;
    }

    void log(String message) {
        println &quot;${Thread.currentThread()} - ${new Date().format(&#039;HH:mm:ss&#039;)} - ${message}&quot;
    }

    List&amp;lt;Employee&gt; lookup(List&amp;lt;Integer&gt; userIds) {
        ???
    }

    void run() {
        def start = System.currentTimeMillis()

        def employees = lookup(&#x5B;1, 2, 3, 4, 5])

        def end = System.currentTimeMillis()

        println &#039;---------------------------------&#039;
        println &quot;Total time in seconds: ${(end - start) / 1000}&quot;
        println &#039;---------------------------------&#039;

        employees.each {
            println it
        }
    }

    static void main(String&#x5B;] args) {
        new App().run()
    }
}
</pre></div>


<p>We are going to explore multiple solutions to implement <code>lookup(..)</code> to run as fast as possible.</p>



<h2 class="wp-block-heading">ATTEMPT 1</h2>



<p>The simplest and the most straightforward approach is to perform the task synchronously.</p>



<p>Code:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: groovy; title: ; notranslate">
List&lt;Employee&gt; lookup(List&lt;Integer&gt; userIds) {
    userIds.collect { id -&gt;
        new Employee(
                id: id,
                name: nameLookup(id),
                address: addressLookup(id)
        )
    }
}
</pre></div>


<p>Output:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
Thread&#x5B;main,5,main] - 20:54:09 - Name lookup: 1
Thread&#x5B;main,5,main] - 20:54:11 - Addr lookup: 1
Thread&#x5B;main,5,main] - 20:54:15 - Name lookup: 2
Thread&#x5B;main,5,main] - 20:54:17 - Addr lookup: 2
Thread&#x5B;main,5,main] - 20:54:21 - Name lookup: 3
Thread&#x5B;main,5,main] - 20:54:23 - Addr lookup: 3
Thread&#x5B;main,5,main] - 20:54:27 - Name lookup: 4
Thread&#x5B;main,5,main] - 20:54:29 - Addr lookup: 4
Thread&#x5B;main,5,main] - 20:54:33 - Name lookup: 5
Thread&#x5B;main,5,main] - 20:54:35 - Addr lookup: 5
---------------------------------
Total time in seconds: 30.129
---------------------------------
Employee(1, User 1, Address 1)
Employee(2, User 2, Address 2)
Employee(3, User 3, Address 3)
Employee(4, User 4, Address 4)
Employee(5, User 5, Address 5)
</pre></div>


<p>Since everything runs synchronously in one thread, it takes about 30 seconds to complete.</p>



<h2 class="wp-block-heading">ATTEMPT 2</h2>



<p>In this attempt and the rest of the attempts, we are going to use GPars, which is a concurrency and parallelism library.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: xml; title: ; notranslate">
&lt;dependency&gt;
    &lt;groupId&gt;org.codehaus.gpars&lt;/groupId&gt;
    &lt;artifactId&gt;gpars&lt;/artifactId&gt;
    &lt;version&gt;1.2.1&lt;/version&gt;
&lt;/dependency&gt;
</pre></div>


<p>In this attempt, we are going to use <code>GParsPool.executeAsyncAndWait(..)</code>.</p>



<p>Code:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: groovy; title: ; notranslate">
List&lt;Employee&gt; lookup(List&lt;Integer&gt; userIds) {
    (List&lt;Employee&gt;) GParsPool.withPool {
        userIds.collect { id -&gt;
            def results = GParsPool.executeAsyncAndWait(
                    this.&amp;nameLookup.curry(id),
                    this.&amp;addressLookup.curry(id)
            )

            new Employee(
                    id: id,
                    name: results&#x5B;0],
                    address: results&#x5B;1]
            )
        }
    }
}
</pre></div>


<p>Output:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
Thread&#x5B;ForkJoinPool-1-worker-2,5,main] - 20:54:40 - Addr lookup: 1
Thread&#x5B;ForkJoinPool-1-worker-1,5,main] - 20:54:40 - Name lookup: 1
Thread&#x5B;ForkJoinPool-1-worker-2,5,main] - 20:54:44 - Name lookup: 2
Thread&#x5B;ForkJoinPool-1-worker-1,5,main] - 20:54:44 - Addr lookup: 2
Thread&#x5B;ForkJoinPool-1-worker-1,5,main] - 20:54:48 - Name lookup: 3
Thread&#x5B;ForkJoinPool-1-worker-2,5,main] - 20:54:48 - Addr lookup: 3
Thread&#x5B;ForkJoinPool-1-worker-1,5,main] - 20:54:52 - Addr lookup: 4
Thread&#x5B;ForkJoinPool-1-worker-2,5,main] - 20:54:52 - Name lookup: 4
Thread&#x5B;ForkJoinPool-1-worker-2,5,main] - 20:54:56 - Addr lookup: 5
Thread&#x5B;ForkJoinPool-1-worker-1,5,main] - 20:54:56 - Name lookup: 5
---------------------------------
Total time in seconds: 20.184
---------------------------------
Employee(1, User 1, Address 1)
Employee(2, User 2, Address 2)
Employee(3, User 3, Address 3)
Employee(4, User 4, Address 4)
Employee(5, User 5, Address 5)
</pre></div>


<p>This allows us to run both the name lookup and the address lookup concurrently for each user ID.</p>



<p><b>Speed gain compared to first attempt: 1.5x</b></p>



<h2 class="wp-block-heading">ATTEMPT 3</h2>



<p>How about <code>collectParallel(..)</code>?</p>



<p>Code:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: groovy; title: ; notranslate">
List&lt;Employee&gt; lookup(List&lt;Integer&gt; userIds) {
    (List&lt;Employee&gt;) GParsPool.withPool {
        userIds.collectParallel { Integer id -&gt;
            new Employee(
                    id: id,
                    name: nameLookup(id),
                    address: addressLookup(id)
            )
        }
    }
}
</pre></div>


<p>Output:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
Thread&#x5B;ForkJoinPool-2-worker-1,5,main] - 20:55:00 - Name lookup: 1
Thread&#x5B;ForkJoinPool-2-worker-4,5,main] - 20:55:00 - Name lookup: 4
Thread&#x5B;ForkJoinPool-2-worker-3,5,main] - 20:55:00 - Name lookup: 2
Thread&#x5B;ForkJoinPool-2-worker-2,5,main] - 20:55:00 - Name lookup: 3
Thread&#x5B;ForkJoinPool-2-worker-5,5,main] - 20:55:00 - Name lookup: 5
Thread&#x5B;ForkJoinPool-2-worker-4,5,main] - 20:55:02 - Addr lookup: 4
Thread&#x5B;ForkJoinPool-2-worker-3,5,main] - 20:55:02 - Addr lookup: 2
Thread&#x5B;ForkJoinPool-2-worker-1,5,main] - 20:55:02 - Addr lookup: 1
Thread&#x5B;ForkJoinPool-2-worker-2,5,main] - 20:55:02 - Addr lookup: 3
Thread&#x5B;ForkJoinPool-2-worker-5,5,main] - 20:55:02 - Addr lookup: 5
---------------------------------
Total time in seconds: 6.156
---------------------------------
Employee(1, User 1, Address 1)
Employee(2, User 2, Address 2)
Employee(3, User 3, Address 3)
Employee(4, User 4, Address 4)
Employee(5, User 5, Address 5)
</pre></div>


<p>This allows us to run all name lookups concurrently, followed by all address lookup concurrently.</p>



<p><b>Speed gain compared to first attempt: 4.9x</b></p>



<h2 class="wp-block-heading">ATTEMPT 4</h2>



<p>Perhaps, another approach is to kick start all the lookups asynchronously and hold on to the returned <code>Future</code> objects:-</p>



<p>Code:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: groovy; title: ; notranslate">
List&lt;Employee&gt; lookup(List&lt;Integer&gt; userIds) {
    (List&lt;Employee&gt;) GParsPool.withPool {
        List&lt;Future&gt; nameFutures = userIds.collect {
            this.&amp;nameLookup.callAsync(it)
        }

        List&lt;Future&gt; addressFutures = userIds.collect {
            this.&amp;addressLookup.callAsync(it)
        }

        userIds.withIndex().collect { Integer id, Integer i -&gt;
            new Employee(
                    id: id,
                    name: nameFutures&#x5B;i].get(),
                    address: addressFutures&#x5B;i].get()
            )
        }
    }
}
</pre></div>


<p>Output:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
Thread&#x5B;ForkJoinPool-3-worker-5,5,main] - 20:55:06 - Name lookup: 5
Thread&#x5B;ForkJoinPool-3-worker-4,5,main] - 20:55:06 - Name lookup: 4
Thread&#x5B;ForkJoinPool-3-worker-2,5,main] - 20:55:06 - Name lookup: 2
Thread&#x5B;ForkJoinPool-3-worker-3,5,main] - 20:55:06 - Name lookup: 3
Thread&#x5B;ForkJoinPool-3-worker-1,5,main] - 20:55:06 - Name lookup: 1
Thread&#x5B;ForkJoinPool-3-worker-3,5,main] - 20:55:08 - Addr lookup: 4
Thread&#x5B;ForkJoinPool-3-worker-2,5,main] - 20:55:08 - Addr lookup: 3
Thread&#x5B;ForkJoinPool-3-worker-4,5,main] - 20:55:08 - Addr lookup: 2
Thread&#x5B;ForkJoinPool-3-worker-5,5,main] - 20:55:08 - Addr lookup: 1
Thread&#x5B;ForkJoinPool-3-worker-1,5,main] - 20:55:08 - Addr lookup: 5
---------------------------------
Total time in seconds: 6.032
---------------------------------
Employee(1, User 1, Address 1)
Employee(2, User 2, Address 2)
Employee(3, User 3, Address 3)
Employee(4, User 4, Address 4)
Employee(5, User 5, Address 5)
</pre></div>


<p>It&#8217;s slightly better than the previous attempt, but the performance gain is rather negligible.</p>



<p><b>Speed gain compared to first attempt: 5.0x</b></p>



<h2 class="wp-block-heading">ATTEMPT 5</h2>



<p>What if we take the previous attempt and increase the number of threads to 10?</p>



<p>Code:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: groovy; highlight: [2]; title: ; notranslate">
List&lt;Employee&gt; lookup(List&lt;Integer&gt; userIds) {
    GParsPool.withPool 10, {
        List&lt;Future&gt; nameFutures = userIds.collect {
            this.&amp;nameLookup.callAsync(it)
        }

        List&lt;Future&gt; addressFutures = userIds.collect {
            this.&amp;addressLookup.callAsync(it)
        }

        userIds.withIndex().collect { Integer id, Integer i -&gt;
            new Employee(
                    id: id,
                    name: nameFutures&#x5B;i].get(),
                    address: addressFutures&#x5B;i].get()
            )
        }
    }
}
</pre></div>


<p>Output:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
Thread&#x5B;ForkJoinPool-4-worker-1,5,main] - 20:55:12 - Name lookup: 1
Thread&#x5B;ForkJoinPool-4-worker-2,5,main] - 20:55:12 - Name lookup: 2
Thread&#x5B;ForkJoinPool-4-worker-3,5,main] - 20:55:12 - Name lookup: 3
Thread&#x5B;ForkJoinPool-4-worker-4,5,main] - 20:55:12 - Name lookup: 4
Thread&#x5B;ForkJoinPool-4-worker-5,5,main] - 20:55:12 - Name lookup: 5
Thread&#x5B;ForkJoinPool-4-worker-6,5,main] - 20:55:12 - Addr lookup: 1
Thread&#x5B;ForkJoinPool-4-worker-8,5,main] - 20:55:12 - Addr lookup: 3
Thread&#x5B;ForkJoinPool-4-worker-7,5,main] - 20:55:12 - Addr lookup: 2
Thread&#x5B;ForkJoinPool-4-worker-9,5,main] - 20:55:12 - Addr lookup: 4
Thread&#x5B;ForkJoinPool-4-worker-10,5,main] - 20:55:12 - Addr lookup: 5
---------------------------------
Total time in seconds: 4.016
---------------------------------
Employee(1, User 1, Address 1)
Employee(2, User 2, Address 2)
Employee(3, User 3, Address 3)
Employee(4, User 4, Address 4)
Employee(5, User 5, Address 5)
</pre></div>


<p><b>Speed gain compared to first attempt: 7.5x</b></p>



<p>And now, we have successfully improve our implementation performance from 30 seconds to 4 seconds.</p>
<p>The post <a rel="nofollow" href="https://myshittycode.com/2017/04/06/groovy-gpars-handling-concurrency/">Groovy + GPars: Handling Concurrency</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://myshittycode.com/2017/04/06/groovy-gpars-handling-concurrency/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">939</post-id>	</item>
		<item>
		<title>IntelliJ IDEA 14.1: Better equals(), hashCode() and toString()</title>
		<link>https://myshittycode.com/2015/07/21/intellij-idea-14-1-better-equals-hashcode-and-tostring/</link>
					<comments>https://myshittycode.com/2015/07/21/intellij-idea-14-1-better-equals-hashcode-and-tostring/#respond</comments>
		
		<dc:creator><![CDATA[Shitty Author]]></dc:creator>
		<pubDate>Tue, 21 Jul 2015 15:23:47 +0000</pubDate>
				<category><![CDATA[Programming Language]]></category>
		<category><![CDATA[Development Tools]]></category>
		<category><![CDATA[Guava]]></category>
		<category><![CDATA[IntelliJ IDEA]]></category>
		<category><![CDATA[Java]]></category>
		<guid isPermaLink="false">http://myshittycode.com/?p=740</guid>

					<description><![CDATA[<p>PROBLEM Let&#8217;s assume we want to create the default equals(), hashCode() and toString() with the following bean:- Most IDEs, including older version of IntelliJ, have code generation features that would create something similar to this:- While it works, the generated code is usually crazy horrendous. SOLUTION With IntelliJ 14.x, it allows us to select templates [&#8230;]</p>
<p>The post <a rel="nofollow" href="https://myshittycode.com/2015/07/21/intellij-idea-14-1-better-equals-hashcode-and-tostring/">IntelliJ IDEA 14.1: Better equals(), hashCode() and toString()</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">PROBLEM</h2>



<p>Let&#8217;s assume we want to create the default <b>equals()</b>, <b>hashCode()</b> and <b>toString()</b> with the following bean:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
public final class Person {
    private final String name;
    private final Collection&lt;car&gt; cars;

    public Person(final String name, final Collection&lt;car&gt; cars) {
        this.name = name;
        this.cars = cars;
    }

    public String getName() {
        return name;
    }

    public Collection&lt;car&gt; getCars() {
        return cars;
    }
}
</pre></div>


<p>Most IDEs, including older version of IntelliJ, have code generation features that would create something similar to this:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
public final class Person {
    ...

    @Override
    public boolean equals(final Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        final Person person = (Person) o;

        if (name != null ? !name.equals(person.name) : person.name != null) {
            return false;
        }
        return !(cars != null ? !cars.equals(person.cars) : person.cars != null);
    }

    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + (cars != null ? cars.hashCode() : 0);
        return result;
    }

    @Override
    public String toString() {
        return &quot;Person{&quot; +
               &quot;name=&#039;&quot; + name + &#039;\&#039;&#039; +
               &quot;, cars=&quot; + cars +
               &#039;}&#039;;
    }
}
</pre></div>


<p>While it works, the generated code is usually crazy horrendous.</p>



<h2 class="wp-block-heading">SOLUTION</h2>



<p>With IntelliJ 14.x, it allows us to select templates from several proven libraries.</p>



<p>To generate <b>equals()</b> and <b>hashCode()</b>, select <b>equals() and hashCode()</b> option from the <b>Generate</b> pop-up dialog:-</p>



<figure class="wp-block-image aligncenter"><img fetchpriority="high" decoding="async" width="496" height="378" src="https://myshittycode.com/wp-content/uploads/2015/07/screen-shot-2015-07-21-at-10-08-23-am-1.png?x45560" alt="" class="wp-image-745" srcset="https://myshittycode.com/wp-content/uploads/2015/07/screen-shot-2015-07-21-at-10-08-23-am-1.png 496w, https://myshittycode.com/wp-content/uploads/2015/07/screen-shot-2015-07-21-at-10-08-23-am-1-300x229.png 300w" sizes="(max-width: 496px) 100vw, 496px" /></figure>



<p>There are several templates to choose from:-</p>



<figure class="wp-block-image aligncenter"><img decoding="async" width="482" height="382" src="https://myshittycode.com/wp-content/uploads/2015/07/screen-shot-2015-07-21-at-10-09-05-am-1.png?x45560" alt="" class="wp-image-746" srcset="https://myshittycode.com/wp-content/uploads/2015/07/screen-shot-2015-07-21-at-10-09-05-am-1.png 482w, https://myshittycode.com/wp-content/uploads/2015/07/screen-shot-2015-07-21-at-10-09-05-am-1-300x238.png 300w" sizes="(max-width: 482px) 100vw, 482px" /></figure>



<p>Here&#8217;s an example of <b>equals()</b> and <b>hashCode()</b> using Guava and getter methods:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
public final class Person {
    ...

    @Override
    public boolean equals(final Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        final Person person = (Person) o;
        return Objects.equal(getName(), person.getName()) &amp;amp;amp;&amp;amp;amp;
               Objects.equal(getCars(), person.getCars());
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(getName(), getCars());
    }
}
</pre></div>


<p>To generate <b>toString()</b>, select <b>toString()</b> option from the <b>Generate</b> pop-up dialog:-</p>



<figure class="wp-block-image aligncenter"><img decoding="async" width="395" height="313" src="https://myshittycode.com/wp-content/uploads/2015/07/screen-shot-2015-07-21-at-10-10-06-am-1.png?x45560" alt="" class="wp-image-747" srcset="https://myshittycode.com/wp-content/uploads/2015/07/screen-shot-2015-07-21-at-10-10-06-am-1.png 395w, https://myshittycode.com/wp-content/uploads/2015/07/screen-shot-2015-07-21-at-10-10-06-am-1-300x238.png 300w" sizes="(max-width: 395px) 100vw, 395px" /></figure>



<p>Again, there are several templates to choose from:-</p>



<figure class="wp-block-image aligncenter"><img loading="lazy" decoding="async" width="504" height="298" src="https://myshittycode.com/wp-content/uploads/2015/07/screen-shot-2015-07-21-at-10-10-45-am-1.png?x45560" alt="" class="wp-image-748" srcset="https://myshittycode.com/wp-content/uploads/2015/07/screen-shot-2015-07-21-at-10-10-45-am-1.png 504w, https://myshittycode.com/wp-content/uploads/2015/07/screen-shot-2015-07-21-at-10-10-45-am-1-300x177.png 300w" sizes="auto, (max-width: 504px) 100vw, 504px" /></figure>



<p>Here&#8217;s an example of <b>toString()</b> using Guava:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
public final class Person {
    ...

    @Override
    public String toString() {
        return Objects.toStringHelper(this)
                .add(&quot;name&quot;, name)
                .add(&quot;cars&quot;, cars)
                .toString();
    }
}
</pre></div><p>The post <a rel="nofollow" href="https://myshittycode.com/2015/07/21/intellij-idea-14-1-better-equals-hashcode-and-tostring/">IntelliJ IDEA 14.1: Better equals(), hashCode() and toString()</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://myshittycode.com/2015/07/21/intellij-idea-14-1-better-equals-hashcode-and-tostring/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">740</post-id>	</item>
		<item>
		<title>Guava: Testing equals(..) and hashcode(..)</title>
		<link>https://myshittycode.com/2015/04/28/guava-testing-equals-and-hashcode/</link>
					<comments>https://myshittycode.com/2015/04/28/guava-testing-equals-and-hashcode/#respond</comments>
		
		<dc:creator><![CDATA[Shitty Author]]></dc:creator>
		<pubDate>Tue, 28 Apr 2015 15:45:29 +0000</pubDate>
				<category><![CDATA[Programming Language]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Guava]]></category>
		<category><![CDATA[Spock]]></category>
		<guid isPermaLink="false">http://myshittycode.com/?p=698</guid>

					<description><![CDATA[<p>PROBLEM Let&#8217;s assume we want to test the following equals(..):- A correctly implemented equals(..) must be reflexive, symmetric, transitive, consistent and handles null comparison. In another word, you have to write test cases to pass at least these 5 rules. Anything less is pure bullshit. SOLUTION You can write these tests yourself&#8230; or you can [&#8230;]</p>
<p>The post <a rel="nofollow" href="https://myshittycode.com/2015/04/28/guava-testing-equals-and-hashcode/">Guava: Testing equals(..) and hashcode(..)</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">PROBLEM</h2>



<p>Let&#8217;s assume we want to test the following <b>equals(..)</b>:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; highlight: [5,6,7,8,9,10,11,12,13]; title: ; notranslate">
public class Person {
    private String name;
    private int age;

    @Override
    public boolean equals(Object o) {
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        Person person = (Person) o;
        return Objects.equal(name, person.name);
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(name);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
</pre></div>


<p>A correctly implemented <b>equals(..)</b> must be reflexive, symmetric, transitive, consistent and handles null comparison.</p>



<p>In another word, you have to write test cases to pass at least these 5 rules. Anything less is pure bullshit.</p>



<h2 class="wp-block-heading">SOLUTION</h2>



<p>You can write these tests yourself&#8230; or you can leverage Guava&#8217;s EqualsTester. This library will test these 5 rules and ensure the generated hashcode matches too.</p>



<p>First, include the needed dependency:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: xml; title: ; notranslate">
&lt;dependency&gt;
    &lt;groupid&gt;com.google.guava&lt;/groupid&gt;
    &lt;artifactid&gt;guava-testlib&lt;/artifactid&gt;
    &lt;version&gt;18.0&lt;/version&gt;
    &lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
</pre></div>


<p>Instead of writing JUnit tests, I&#8217;ll be writing Spock specs, which is essentially built on top of Groovy, because it allows me to write very clear and clean tests.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: groovy; title: ; notranslate">
class PersonSpec extends Specification {

    def person = new Person(name: &#039;Mike&#039;, age: 10)

    def &quot;equals - equal&quot;() {
        when:
        new EqualsTester().
                addEqualityGroup(person,
                                 new Person(name: &#039;Mike&#039;, age: 10),
                                 new Person(name: &#039;Mike&#039;, age: 20)).
                testEquals()

        then:
        notThrown(AssertionFailedError.class)
    }

    def &quot;equals - not equal&quot;() {
        when:
        new EqualsTester().
                addEqualityGroup(person,
                                 new Person(name: &#039;Kurt&#039;, age: 10)).
                testEquals()

        then:
        thrown(AssertionFailedError.class)
    }
}
</pre></div><p>The post <a rel="nofollow" href="https://myshittycode.com/2015/04/28/guava-testing-equals-and-hashcode/">Guava: Testing equals(..) and hashcode(..)</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://myshittycode.com/2015/04/28/guava-testing-equals-and-hashcode/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">698</post-id>	</item>
		<item>
		<title>Guava: Reducing Cyclomatic Complexity with Objects.firstNonNull(&#8230;)</title>
		<link>https://myshittycode.com/2014/10/28/guava-reducing-cyclomatic-complexity-with-objects-firstnonnull/</link>
					<comments>https://myshittycode.com/2014/10/28/guava-reducing-cyclomatic-complexity-with-objects-firstnonnull/#respond</comments>
		
		<dc:creator><![CDATA[Shitty Author]]></dc:creator>
		<pubDate>Tue, 28 Oct 2014 15:29:28 +0000</pubDate>
				<category><![CDATA[Programming Language]]></category>
		<category><![CDATA[Guava]]></category>
		<guid isPermaLink="false">http://myshittycode.com/?p=622</guid>

					<description><![CDATA[<p>PROBLEM Ever written code like this? While it works, it has several minor problems:- SOLUTION Guava provides a much cleaner solution to address these problems:-</p>
<p>The post <a rel="nofollow" href="https://myshittycode.com/2014/10/28/guava-reducing-cyclomatic-complexity-with-objects-firstnonnull/">Guava: Reducing Cyclomatic Complexity with Objects.firstNonNull(&#8230;)</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">PROBLEM</h2>



<p>Ever written code like this?</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
Employee employee = employeeService.getByName(employeeName);

if (employee == null) {
    employee = new Employee();
}
</pre></div>


<p>While it works, it has several minor problems:-</p>



<ul class="wp-block-list">
<li>The above code has cyclomatic complexity of 2 due to the <code>if</code> logic.</li>



<li>We cannot define <code>final</code> on <code>employee</code> object.</li>



<li>Too many lines of code, and seriously, it looks very 2003.</li>
</ul>



<h2 class="wp-block-heading">SOLUTION</h2>



<p>Guava provides a much cleaner solution to address these problems:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
final Employee employee = Objects.firstNonNull(employeeService.getByName(employeeName),
                                               new Employee());
</pre></div><p>The post <a rel="nofollow" href="https://myshittycode.com/2014/10/28/guava-reducing-cyclomatic-complexity-with-objects-firstnonnull/">Guava: Reducing Cyclomatic Complexity with Objects.firstNonNull(&#8230;)</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://myshittycode.com/2014/10/28/guava-reducing-cyclomatic-complexity-with-objects-firstnonnull/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">622</post-id>	</item>
		<item>
		<title>Guava: FluentIterable vs Collections2</title>
		<link>https://myshittycode.com/2014/10/27/guava-fluentiterable-vs-collections2/</link>
					<comments>https://myshittycode.com/2014/10/27/guava-fluentiterable-vs-collections2/#respond</comments>
		
		<dc:creator><![CDATA[Shitty Author]]></dc:creator>
		<pubDate>Mon, 27 Oct 2014 19:26:11 +0000</pubDate>
				<category><![CDATA[Programming Language]]></category>
		<category><![CDATA[Guava]]></category>
		<guid isPermaLink="false">http://myshittycode.com/?p=619</guid>

					<description><![CDATA[<p>PROBLEM Guava&#8217;s Collections2 is great when dealing with collections, but it quickly becomes rather clumsy and messy when we try to combine multiple actions together. For example, say we have userIds, which is a collection of user IDs. For each user ID, we want to retrieve the Employee object and add it into an immutable [&#8230;]</p>
<p>The post <a rel="nofollow" href="https://myshittycode.com/2014/10/27/guava-fluentiterable-vs-collections2/">Guava: FluentIterable vs Collections2</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">PROBLEM</h2>



<p>Guava&#8217;s <code>Collections2</code> is great when dealing with collections, but it quickly becomes rather clumsy and messy when we try to combine multiple actions together.</p>



<p>For example, say we have <code>userIds</code>, which is a collection of user IDs. For each user ID, we want to retrieve the <code>Employee</code> object and add it into an immutable set if the lookup is successful. So, we essentially want to perform a &#8220;tranform&#8221; and &#8220;filter&#8221; here.</p>



<p>By using strictly <code>Collections2</code>, we ended up with the following code:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
final ImmutableSet&lt;Employee&gt; employees = ImmutableSet.copyOf(
        Collections2.filter(
                Collections2.transform(userIds,
                                       new Function&lt;String, Employee&gt;() {
                                           @Override
                                           public Employee apply(String userId) {
                                               return employeeService.getEmployee(userId);
                                           }
                                       }),
                new Predicate&lt;Employee&gt;() {
                    @Override
                    public boolean apply(Employee employee) {
                        return employee != null;
                    }
                }));
</pre></div>


<p>While it works, it may be confusing to those reading the code due to the nested functions.</p>



<h2 class="wp-block-heading">SOLUTION</h2>



<p>A better approach is to use <code>FluentIterable</code> that allows us to write more natural top-to-bottom code:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
final ImmutableSet&lt;Employee&gt; employees = FluentIterable
        .from(userIds)
        .transform(new Function&lt;String, Employee&gt;() {
            @Override
            public Employee apply(String userId) {
                return employeeService.getEmployee(userId);
            }
        })
        .filter(new Predicate&lt;Employee&gt;() {
            @Override
            public boolean apply(Employee employee) {
                return employee != null;
            }
        })
        .toImmutableSet();
</pre></div><p>The post <a rel="nofollow" href="https://myshittycode.com/2014/10/27/guava-fluentiterable-vs-collections2/">Guava: FluentIterable vs Collections2</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://myshittycode.com/2014/10/27/guava-fluentiterable-vs-collections2/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">619</post-id>	</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 
Lazy Loading (feed)
Database Caching 52/73 queries in 0.073 seconds using Disk

Served from: myshittycode.com @ 2026-02-20 23:11:09 by W3 Total Cache
-->