Flying Bytes Guides for Java/Kotlin, Functional Programming and All Things Android flyingbytes.github.io/ Fri, 31 Oct 2025 10:37:40 +0000 Fri, 31 Oct 2025 10:37:40 +0000 Jekyll v3.10.0 How Google Shut Down My Android Play Store Account and Killed My Business <p><strong>TL;DR:</strong> On May 29th, 2025, Google has shut down my Google Play Store developer account, thus blocking all of my apps and killing my business of publishing Android apps. They’ve given me no reason at all, and don’t allow me to take any action to re-activate my account. It seems like moving my apps to a new account, an idea that originated from the <a href="#newA">Google support</a> itself, caused the termination.</p> <p><em>In case Google’s reading this, my ticket numbers are 0-2181000039046 (new account) and 5-7732000037267 (old account).</em></p> <p>Update August 2025: Someone mentioned that I should have deleted my old account by hand instead of letting it automatically block. However, since then I’ve been able to re-enable the old account and properly delete it. However, the new account is still blocked and Google support does not want to enable it. So that’s also not the issue I’m facing</p> <p>Over the years, I’ve read in multiple blog posts like <a href="https://medium.com/@raffaelet/my-seven-years-old-google-play-developer-account-has-been-terminated-ed321754cd51">this</a>, <a href="https://www.reddit.com/r/androiddev/comments/1clee9k/company_account_got_terminated_for_vague_reason/?share_id=jnvFTWsncgXF-CKVOCjCk&amp;utm_content=1&amp;utm_medium=android_app&amp;utm_name=androidcss&amp;utm_source=share&amp;utm_term=1">this</a>, or <a href="https://www.reddit.com/r/androiddev/comments/1cle2uj/google_developer_account_terminated_after_getting/">that</a> about Google shutting down other people’s developer accounts for arbitrary reasons.</p> <p>I’ve never thought this arbitrary termination could happen to me as well. However, on May 29th, 2025, exactly this worst-case scenario began to unfold.</p> <p>In this post, I want to present my frustrating conversations with the Google support about this incident and how Google declines any help to reactivate my account. The goal of this post is to show how easy it is to loose your business if you lay it in the hands of a third party like Google.</p> <p>First, I’ll tell the main points of the story. <a href="#longL">Later</a>, I will go into more detail and publish my conversations with the Google support.</p> <h2 id="long-story-short">Long story short</h2> <p>In case you didn’t know, Google insists to verify the legal name and address of every Play Store developer account since <a href="https://support.google.com/googleplay/android-developer/answer/14177239?hl=en">May 2024</a>. Furthermore, if you monetize apps, this highly confidential information will be easily accessible for every user of the Play Store, even if you are not logged in. Hence, scraping and storing legal information is pretty easy in this case.</p> <p>I’m fine with Google checking my legal information. However, I’m not fine making this sensitive information publicly available. Hence, I’ve decided to make all of monetized apps free s.t. my information is kept private. Furthermore, the Google support told me that I’d have to create a new developer account and move all apps there. This is because my old account contained monetized apps in the past, hence I’d have to make my legal information publicly available even if I don’t have monetized apps right now. The idea was to verify my new account and let my old and empty account suspend without any information provided. So far, so good.</p> <p>On May 14th, 2025, my old account was suspended as this was the deadline for providing legal information. However, two weeks later, on May 29th, 2025, my new account with all apps was suspended as well.</p> <p><a href="https://www.reddit.com/r/androiddev/comments/1clee9k/comment/l2t2rhe/?utm_source=share&amp;utm_medium=web3x&amp;utm_name=web3xcss&amp;utm_term=1&amp;utm_content=share_button">This Reddit comment</a> points out that moving my apps probably caused the termination of the new account. Google seems to automatically suspend accounts that are “connected” to suspended accounts. As my old account was suspended (which is fine for me), my connected new account was suspended as well (which is not fine for me). As I’ve not update any apps in my developer accounts in the days prior and not changed any settings, this seems to be the logical conclusion.</p> <p>However, opening an appeal and pointing out that this transfer of apps was suggested by Google itself didn’t help to change Google’s opinion on the matter. As I can’t be 100% sure that the transfer is the actual cause of the termination (as Google doesn’t provide me the exact reason), there is nothing more I can’t do. My account is still suspended to this day.</p> <p><a name="longL"></a></p> <h2 id="long-story-long">Long story long</h2> <p>Explanation: In this part of the story, I will copy-paste parts of the email conversation between the Google support and me. The most important part of every email is surrounded by “**“-marks</p> <p>I’m creating and publishing Android apps since 2015. In 2017, I’ve started monetizing them and making some money with them. Over the years, many of my apps gained traction, and some even got used in the context of university lectures. I’ve learned a lot by creating the business, working with the Google developer account and publishing a dozen apps.</p> <p>At the beginning of 2025, I’ve had to make a decision. Either making it extremely easy for every Play Store user to see my legal address on every app page (even not logged in users like bots), or demonetizing all of my apps.</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Thanks for your reply. I understand that you are having some concerns in regards to the new requirements related to the information that will be shown publicly on the Play Store. As part of the new expanded developer verification requirements, developers will be required to provide certain information when creating Play Console which helps us to verify your identity and making sure that we provide safe and wonderful app experiences for our users and a great opportunity for all our developers to be successful. - For individual accounts, below are the details that will be shown publicly: - Developer name - Legal name - Country (taken from legal address) - Developer email address **Kindly note that, if you decide to monetize your app on Google Play then Google will display your full address.** In addition, there are certain countries or regions that may require you to complete additional requirements to comply with regulatory authorities. For further information, you may refer to this *Help center article* &lt;https://support.google.com/googleplay/android-developer/answer/6223646?hl=en&amp;ref_topic=12798386&amp;sjid=17803400505414581127-AP&gt; . To learn more about developer verifications, please visit *Play Console Requirements* &lt;https://support.google.com/googleplay/android-developer/answer/10788890?hl=en&gt; and the *Play Console Help Center* &lt;https://support.google.com/googleplay/android-developer/answer/13628312&gt;. Thanks for working with us through this process and please don't hesitate to reply to this email if you need further assistance. If we do not hear from you, we will consider the matter closed. </code></pre></div></div> <p>It also had to be the correct legal address, something like a postbox doesn’t work.</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> Thank you for your patience. **Unfortunately you can't use a postbox address.** Thanks for your understanding. Regards, ... Google Play Developer Support </code></pre></div></div> <p>The decision was pretty hard for me, but I’ve demonetized all of my apps to keep my address safe. For this to work, I’ve moved all of my apps to a new developer account of mine, as the Google support has told me.</p> <p><a name="newA"></a></p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Thank you for your reply. In order to provide transparency to our users, and avoid potential regulatory issues, Google Play now requires all organization developers and all monetizing individual developers to provide a verified address that is displayed in full to Google Play users. **If you do not intend to monetize on Google Play, you can create a new account and transfer your app there, and we will assist you in closing your current account. Individual non-monetizing developer accounts only have their legal name and country of residence publicly displayed, and not the full address.** Thanks for working with us through this process and please don't hesitate to reply to this email if you need further assistance. If we do not hear from you, we will consider the matter closed. </code></pre></div></div> <p>This way, no payment information was linked to my (new) developer account anymore, hence I didn’t have to publicly announce my real address everywhere. So far, so good. That’s the way Google wanted it to be, and I didn’t bother paying the extra 25 dollars for the second developer account. As mentioned, that’s the recommended way from Google to keep my apps and hide my address.</p> <p>However, after two weeks, Google blocked <em>both</em> of my developer accounts without any particular reason. As this transfer was the only thing I did in this time, I guess the suspension is connected to my account migration, as <a href="https://www.reddit.com/r/androiddev/comments/1clee9k/comment/l2t2rhe/?utm_source=share&amp;utm_medium=web3x&amp;utm_name=web3xcss&amp;utm_term=1&amp;utm_content=share_button">this Reddit comment</a> points out as well.</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>This is a notification that your Google Play Publisher account has been terminated. Publishing Status Status: Account Terminated **Your Developer account remains terminated due to prior violations of the Developer Program Policies and Developer Distribution Agreement by this or associated, previously terminated Google Play Developer accounts.** Please do not attempt to register a new developer account. Any new accounts will be closed, and your developer registration fee will not be refunded. View policy status Issue found: High Risk Behavior We have identified a pattern of high risk or abuse associated with your Developer Account and are taking this action pursuant to the Policy Coverage policy. About the Policy Coverage policy We don't allow apps or app content that undermine user trust in the Google Play ecosystem. In assessing whether to include or remove apps from Google Play, we consider a number of factors including, but not limited to, a pattern of harmful behavior or high risk of abuse. We identify risk of abuse including, but not limited to, items such as app- and developer-specific complaints, news reporting, previous violation history, user feedback, and use of popular brands, characters, and other assets. Submit an Appeal Please read through this page to understand your policy violation. If you believe our decision may be incorrect, you can appeal. It may take up to 7 days to receive a response, or longer in exceptional cases. Please do not attempt to register a new developer account. We will not be restoring your account at this time. Regards, ... The Google Play Team </code></pre></div></div> <p>As the email suggests, I’ve submitted an appeal. I’ve asked the Google support team what happened. However, I’ve only got an answer that told me, again, that “strange” behaviour occurred within my account and thus it had to be terminated.</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Thank you for your patience while I looked into your issue. After reviewing your appeal, we're unable to reinstate your Google Play Developer account. We can confirm that we have identified a pattern of high risk or abuse associated with your Developer Account and have taken this action pursuant to Section 8.3 or 10.3 of Google Play’s Developer Distribution Agreement &lt;https://play.google.com/intl/en_us/about/developer-distribution-agreement.html&gt;. **As we previously explained, in order to prevent bad-faith developers from gaming our systems and putting our users at risk in the process, we can’t share the reasons we’ve concluded that your account is at high risk.** Your Developer account remains terminated due to prior violations of the Developer Program Policies &lt;https://play.google.com/about/developer-content-policy/&gt; and Developer Distribution Agreement &lt;https://play.google.com/intl/ALL_us/about/developer-distribution-agreement.html&gt; by this or associated, previously terminated Google Play Developer accounts. Please do not attempt to register a new developer account. Any new accounts will be closed, and your developer registration fee will not be refunded. If you are located in the EU, you may have additional redress options. Learn more about those potential options in the EU Out-of-Court Dispute Resolution Help Center &lt;https://support.google.com/european-union-digital-services-act-redress-options/answer/13535501&gt;. Routing ID: ZLFS Regards, ... The Google Play Team </code></pre></div></div> <p>Asking again which actions I can do to re-activate my account, I’ve received the answer that Google can’t tell me what’s going on because I could start “gaming [Google’s] system”.</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Thanks again for contacting the Google Play team. **As we previously explained, in order to prevent bad-faith developers from gaming our systems and putting our users at risk in the process, we can’t share the reasons we’ve concluded that your account is at high risk.** Your Developer account remains terminated due to prior violations of the Developer Program Policies &lt;https://play.google.com/about/developer-content-policy/&gt; and Developer Distribution Agreement &lt;https://play.google.com/intl/ALL_us/about/developer-distribution-agreement.html&gt; by this or associated, previously terminated Google Play Developer accounts. Please do not attempt to register a new developer account. Any new accounts will be closed, and your developer registration fee will not be refunded. Thank you for your understanding. Regards, ... The Google Play Team Please visit the Google Play *Developer Policy Center* &lt;https://play.google.com/about/developer-content-policy/&gt; and Google Play's *Academy for App Success* &lt;https://www.google.com/url?q=https%3A%2F%2Fplayacademy.exceedlms.com%2Fstudent%2Fcatalog%3Futm_source%3Dshortlink%26utm_medium%3Dgco%26utm_campaign%3Dgeneric&amp;sa=D&amp;sntz=1&amp;usg=AOvVaw3TU58z9sfaZs6auAAx9I4W&gt; to learn more about building policy compliant and high quality apps. You can also visit the *Android Developers Blog* &lt;https://android-developers.googleblog.com/&gt; for the latest Android and Google Play news for app and game developers. </code></pre></div></div> <p>I find it especially rude that they end the conversation with a reference to the developer blog, with information that I’m forbidden to use anymore. Asking again and again, I got the same “gaming the system”-mail three times without any new information whatsoever.</p> <p>I’ve never received a strike in the Play Store before, no bad reviews or whatsoever. I have the rights to the content and names of all of my apps. Still, Google decided that my account had to be terminated.</p> <p>To conclude the post, I just want you to make sure that dependencies on third parties can be good and bad. If you depend on a very powerful third party (like Google) for things to work, it can also happen that things go sideways.</p> Mon, 07 Jul 2025 14:00:00 +0000 flyingbytes.github.io/programming/android/kotlin/context/receiver/contextreceiver/kotlin17/kotlin1620/2025/07/07/Google-Termination.html flyingbytes.github.io/programming/android/kotlin/context/receiver/contextreceiver/kotlin17/kotlin1620/2025/07/07/Google-Termination.html programming android kotlin context receiver contextreceiver kotlin17 kotlin1620 Use C Libraries in Kotlin Native Code (C Interop) for C Noobs <p><strong>TL;DR</strong>: Calling C Code in Kotlin Native is very simple and much more intuitive then using the corresponding JVM-“Java Native Interface” (JNI). However, the sample code from <a href="https://kotlinlang.org/docs/native-c-interop.html">JetBrains</a> is IMHO too hard for C beginners, hence I wrote this blog post. If you just want to see the code, look at <a href="https://github.com/NWuensche/KotlinNativeCInteropProject">GitHub</a>.</p> <p>Hello everybody,</p> <p>When I’m not developing some Android app, I enjoy learning more about the Kotlin Ecosystem as well. As some of you might know, there is not only the “normal” JVM Kotlin programming language, which compiles to bytecode which can be run on the Java Virtual Machine (JVM). There is also “Kotlin Native”, a dialect which compiles to bear-metal binary code and thus does not need a JVM to run. This can lead to potentially faster programs or completely new areas of application for Kotlin Code, like embedded devices which can’t handle a full-blown JVM.</p> <p>Unfortunately, the one downside of Kotlin Native in comparison to “JVM-Kotlin” is the of loss of all Java/JVM-Libraries. The JVM is known for its rich ecosystem of libraries and frameworks. You lose all of that when using Kotlin Native as your program does not use the JVM at all. However, you still have another option left to add other people’s code: through C Libraries. Like on the JVM, there is a rich ecosystem of C-libs which one can use.</p> <p>The big question is: <strong>How do you call C libraries from your Kotlin Native code?</strong></p> <p>There is already a <a href="https://kotlinlang.org/docs/native-c-interop.html">tutorial by JetBrains</a> which answers this question. However, I found it way too difficult for a C beginner like me. For example, I don’t know where header-files or shared objects are located on my computer, and I don’t know how linking C-libraries in general works. For you, my dear readers, I will fill these gaps in this blog post after researching this topic in more detail.</p> <p>In the first part of this blog post, we will link an already existing C-library (VLC) into our Kotlin Native code and play some music with it. We learn more about the C-infrastructure, which files one needs to bind everything together, and how we can use the Gradle build system to call the C code in our Kotlin Code.</p> <p>In the second part of this blog post, we will create our own small C-lib and execute it in our Kotlin Native code. Here, we learn more about C and its build-system in general.</p> <p>This tutorial should work on Linux-, OSX/Mac-, and Windows-Systems.</p> <h2 id="linking-a-c-library-into-your-kotlin-native-code">Linking a C library into your Kotlin Native Code</h2> <p>Next, we will link the VLC-C-Library into our Kotlin Native code. It is a really easy and well documented library to play back music. Our goal is to play back some sound in our Kotlin Native Code through the C-library.</p> <p>For the sake of completeness, I want to mention the JNI. If you have a background in JVM-development, you probably heard of the <a href="https://docs.oracle.com/en/java/javase/18/docs/specs/jni/intro.html">Java Native Interface (JNI)</a>. This is a protocol which allows you to call C code on the JVM. However, it is very cumbersome to use. For example, you have to write additional C-adapter to wrap the C-lib you want to use. With Kotlin Native, all of this is way easier and you don’t have to write any additional adapter-code. Gradle does all of this hard work for you under the hood.</p> <p>We have four small steps to do</p> <ol> <li>Create a new Kotlin Native Project</li> <li>Download the VLC-Library</li> <li>Link the VLC-Files to our Kotlin Native Project</li> <li>Call the library to play back sound.</li> </ol> <h3 id="1---create-a-new-kotlin-native-project">1. - Create a new Kotlin Native Project</h3> <p>To create a new Kotlin Native Project, just install IntelliJ, create a new Project, and there click on “Kotlin Multiplatform -&gt; Native Application”. Let’s call it the “KotlinNativeCInteropProject”. Now finish initialization and build the project.</p> <h3 id="2---download-the-vlc-library">2. - Download the VLC-Library</h3> <p>Next, we will download the VLC files. I can’t just give you the files, because they depend on the architecture of your machine, hence you have to download them through the package manager of your OS (or build them yourself). Most of the time, the package is called something like <code class="language-plaintext highlighter-rouge">libvlc</code>, <code class="language-plaintext highlighter-rouge">vlc-devel</code>, or <code class="language-plaintext highlighter-rouge">vlc-dev</code>. Here are the command for the most common distributions:</p> <p>Ubuntu/Linux Mint/Debian/…: <code class="language-plaintext highlighter-rouge">sudo apt install libvlc-dev</code></p> <p>Fedora/RHEL/CoreOS/…: <code class="language-plaintext highlighter-rouge">sudo dnf install libvlc-devel</code></p> <p>Arch Linux/Manjaro/…: <code class="language-plaintext highlighter-rouge">sudo pacman -S libvlc</code></p> <p>OSX/Mac: brew install –cask vlc</p> <p>Windows: Unfortunately, you have to compile the code yourself from <a href="https://wiki.videolan.org/VLC_Source_code/">source</a>.</p> <p>With this, you download two files. The first one is the <code class="language-plaintext highlighter-rouge">libvlc.so</code> file. This is the “shared object”, which basically contains the actual code of the vlc-library. Under most distributions, it is either located under <code class="language-plaintext highlighter-rouge">/lib</code> or <code class="language-plaintext highlighter-rouge">/lib64</code>. If you look inside the shared object, you will see that it is binary file, so you can’t read it at all. The second file that was installed is <code class="language-plaintext highlighter-rouge">vlc.h</code>. This is the header-file, and it should be located at <code class="language-plaintext highlighter-rouge">/usr/include</code> or <code class="language-plaintext highlighter-rouge">/usr/include/vlc</code>. One can actually read this file, and it tells you which functions the shared object actually contains. In Kotlin terminology, the header is like an “interface” of the shared object “class”.</p> <h3 id="3---link-the-vlc-files-to-our-kotlin-native-project">3. - Link the VLC-Files to our Kotlin Native Project</h3> <p>In the third step, we connect these two vlc-files to our Kotlin project. First of, in our Kotlin project, we create the folders <code class="language-plaintext highlighter-rouge">nativeInterop/cinterop</code>, where <code class="language-plaintext highlighter-rouge">nativeInterop</code> is on the same level as the already existing <code class="language-plaintext highlighter-rouge">nativeMain</code> folder. Note that the “I” in <code class="language-plaintext highlighter-rouge">nativeInterop</code> is uppercase, while the “i” in <code class="language-plaintext highlighter-rouge">cinterop</code> is lowercase (this is important).</p> <p>In the<code class="language-plaintext highlighter-rouge">cinterop</code>-folder, we add a <code class="language-plaintext highlighter-rouge">libvlc.def</code> file, which contains the locations of the vlc-files. This file contains the following configurations:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>compilerOpts = -I /usr/include headers = vlc/vlc.h linkerOpts = -L /lib64 -L /lib64/vlc -L /lib -L /opt/local/lib -L /opt/local/lib/vlc -L /usr/local/opt/ -L /usr/local/opt/vlc -l vlc </code></pre></div></div> <p>The <code class="language-plaintext highlighter-rouge">compilerOpts</code> options tells Gradle where to search for header files (i.e. in the <code class="language-plaintext highlighter-rouge">/usr/include</code> folder). The <code class="language-plaintext highlighter-rouge">headers</code> option tells Gradle that we want to add the <code class="language-plaintext highlighter-rouge">/usr/include/vlc/vlc.h</code> header to our project. In the <code class="language-plaintext highlighter-rouge">linkerOpts</code> option, the <code class="language-plaintext highlighter-rouge">-L</code> parameters tell Gradle where to search for shared-object files. I added a lot of different folders so that this project runs on as many distributions as possible, but you can remove the unnecessary ones if you want to. The <code class="language-plaintext highlighter-rouge">-l</code> parameter in the end tells Gradle that we want to add the <code class="language-plaintext highlighter-rouge">libvlc.so</code> file to our project. As you can see, to add <code class="language-plaintext highlighter-rouge">libX.so</code> file to our project, the parameters has to be <code class="language-plaintext highlighter-rouge">-l X</code>.</p> <p>If you work on Windows, you have to adapter the <code class="language-plaintext highlighter-rouge">compilerOpts</code> and <code class="language-plaintext highlighter-rouge">linkerOpts</code> to point to the folder of your <code class="language-plaintext highlighter-rouge">vlc.h</code> and <code class="language-plaintext highlighter-rouge">libvlc.so</code> file.</p> <p>Afterwards, we have to tell Gradle that it should execute the <code class="language-plaintext highlighter-rouge">libvlc.def</code>-file and create Kotlin bindings for the C function which are part of the vlc-header. We do this by adding the following code in our <code class="language-plaintext highlighter-rouge">build.gradle.kts</code> file, and there in the already existing <code class="language-plaintext highlighter-rouge">nativeTarget.apply</code> block:</p> <div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">nativeTarget</span><span class="p">.</span><span class="nf">apply</span> <span class="p">{</span> <span class="o">..</span><span class="p">.</span> <span class="n">compilations</span><span class="p">.</span><span class="nf">getByName</span><span class="p">(</span><span class="s">"main"</span><span class="p">)</span> <span class="p">{</span> <span class="nf">cinterops</span> <span class="p">{</span> <span class="kd">val</span> <span class="py">libvlc</span> <span class="k">by</span> <span class="n">creating</span> <span class="p">}</span> <span class="p">}</span> <span class="o">..</span><span class="p">.</span> <span class="p">}</span> </code></pre></div></div> <p>After we sync the project, Gradle created Kotlin functions that match the functions in the <code class="language-plaintext highlighter-rouge">vlc.h</code> header file. This is an incredible improvement over the JNI, where we had to write these functions ourself.</p> <h3 id="4-call-the-library-to-play-back-sound">4. Call the library to play back sound.</h3> <p>Now, everything is combined and we can use the vlc-library in our project. As Gradle created functions with the same function names as the ones in the vlc-header file, we can easily adapt the <a href="https://wiki.videolan.org/LibVLC_Tutorial/#Sample_libVLC_code">libvlc example code</a> to play back sound for our project. Add the following code to your <code class="language-plaintext highlighter-rouge">Main.kt</code> file:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>import libvlc.* import platform.posix.sleep fun main(args: Array&lt;String&gt;) { val SOUND_FILE = "sound.mp3" val inst = libvlc_new(0, null) val m = libvlc_media_new_path(inst, SOUND_FILE) val mp = libvlc_media_player_new_from_media(m) libvlc_media_release(m) libvlc_media_player_play(mp) sleep(10) } </code></pre></div></div> <p>You can put any <code class="language-plaintext highlighter-rouge">sound.mp3</code> file in the root-“KotlinNativeCInteropProject” folder of your project, or adapt the <code class="language-plaintext highlighter-rouge">SOUND_FILE</code> variable as needed. For example, you could use <a href="https://pixabay.com/sound-effects/dr-tribal-percussion-triplet-loop-high-passed-106bpm-25935/">this file</a>. Our code will play back ten seconds of sounds due to the <code class="language-plaintext highlighter-rouge">sleep(10)</code> command.</p> <p>Hooray, you used C code in your Kotlin project! You can find the final project on <a href="https://github.com/NWuensche/KotlinNativeCInteropProject">GitHub</a>.</p> <p>If your IDE can’t find the <code class="language-plaintext highlighter-rouge">libvlc_...</code>-functions, or can’t import <code class="language-plaintext highlighter-rouge">libvlc.*</code>, then nevertheless try to execute the code by clicking the run arrow next to the <code class="language-plaintext highlighter-rouge">main</code>-function. If this does not work, try to re-sync the Gradle file. For me, it worked by adding a useless character to the <code class="language-plaintext highlighter-rouge">build.gradle.kts</code> file, then syncing (thus creating an error), then removing the character again and re-syncing the project. 99% of the time, this solved the import-issue.</p> <p>Next, we want to take a short detour and create our own C-library and call it from the Kotlin project.</p> <h2 id="create-and-call-your-own-c-library-from-kotlin-native-code">Create and Call your own C Library from Kotlin Native Code</h2> <p>Now, we want to create a small C library called <code class="language-plaintext highlighter-rouge">helloworld</code>. It contains a function <code class="language-plaintext highlighter-rouge">hello()</code> that prints <code class="language-plaintext highlighter-rouge">Hello World!</code> and returns <code class="language-plaintext highlighter-rouge">42</code>. Afterwards we want to call this function from our Kotlin code.</p> <h3 id="create-a-c-library">Create a C library</h3> <p>As you know from the first part of this blog post, we need a shared object and a header file to call C code from our Kotlin project. The header is relatively easy, as it is human readable.</p> <p>Create the file <code class="language-plaintext highlighter-rouge">helloworld.h</code> and insert the following code:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>#include &lt;stdio.h&gt; int hello(); </code></pre></div></div> <p>We need to import the <code class="language-plaintext highlighter-rouge">stdio.h</code> header to call <code class="language-plaintext highlighter-rouge">printf()</code> in the C code afterwards. Next, copy this file to the other header files in the <code class="language-plaintext highlighter-rouge">/usr/include/</code> folder.</p> <p>Next, we need to create a shared object file which contains the actual code. First, we need to create a <code class="language-plaintext highlighter-rouge">helloworld.c</code> file with the following content:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>#include &lt;stdio.h&gt; int hello() { printf("hello world!\n"); return 42; } </code></pre></div></div> <p>As you can see, the function <code class="language-plaintext highlighter-rouge">hello</code> prints “Hello World!” to the console and returns 42.</p> <p>Next, we need to compile this C file to a shared object. We do this with the following command:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gcc -shared -o libhelloworld.so helloworld.c </code></pre></div></div> <p>The command should be rather self-explanatory. We copy the <code class="language-plaintext highlighter-rouge">libhelloworld.so</code> file to <code class="language-plaintext highlighter-rouge">/lib</code>.</p> <p>Afterwards, we do the same things as for the vlc-library. First of, in the <code class="language-plaintext highlighter-rouge">cinterop</code> folder of our Kotlin project, we create a new <code class="language-plaintext highlighter-rouge">libhelloworld.def</code> file with the following content:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>compilerOpts = -I /usr/include headers = helloworld.h linkerOpts = -L /lib64 -L /lib64/vlc -L /lib -L /opt/local/lib -L /opt/local/lib/vlc -L /usr/local/opt/ -L /usr/local/opt/vlc -l helloworld </code></pre></div></div> <p>Next, we add the following line to the <code class="language-plaintext highlighter-rouge">build.gradle.kts</code>:</p> <div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">nativeTarget</span><span class="p">.</span><span class="nf">apply</span> <span class="p">{</span> <span class="o">..</span><span class="p">.</span> <span class="n">compilations</span><span class="p">.</span><span class="nf">getByName</span><span class="p">(</span><span class="s">"main"</span><span class="p">)</span> <span class="p">{</span> <span class="nf">cinterops</span> <span class="p">{</span> <span class="kd">val</span> <span class="py">libvlc</span> <span class="k">by</span> <span class="n">creating</span> <span class="kd">val</span> <span class="py">libhelloworld</span> <span class="k">by</span> <span class="n">creating</span> <span class="c1">//Add this line</span> <span class="p">}</span> <span class="p">}</span> <span class="o">..</span><span class="p">.</span> <span class="p">}</span> </code></pre></div></div> <p>Then sync the project and add the following lines to your <code class="language-plaintext highlighter-rouge">Main.kt</code>:</p> <div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">import</span> <span class="nn">libhelloworld.*</span> <span class="k">fun</span> <span class="nf">main</span><span class="p">(</span><span class="n">args</span><span class="p">:</span> <span class="nc">Array</span><span class="p">&lt;</span><span class="nc">String</span><span class="p">&gt;)</span> <span class="p">{</span> <span class="kd">val</span> <span class="py">x</span> <span class="p">=</span> <span class="nf">hello</span><span class="p">()</span> <span class="c1">//should be 42</span> <span class="nf">println</span><span class="p">(</span><span class="s">"Return value was $x"</span><span class="p">)</span> <span class="p">}</span> </code></pre></div></div> <p>Now, your C should work, congratulations! Again, if it does not compile, try to re-sync the Gradle-file. You can find the final project on <a href="https://github.com/NWuensche/KotlinNativeCInteropProject">GitHub</a>.</p> <h2 id="conclusion">Conclusion</h2> <p>That’s it for today!</p> <p>You have seen the necessary steps to include C code in your Kotlin Native project. Additionally, you have seen how to create a C library yourself.</p> <p>Please leave an email if this post helped you or if you have any questions regarding this blog post.</p> <p>Thanks for reading and have a nice day,</p> <p>Niklas</p> Sat, 10 Sep 2022 09:00:00 +0000 flyingbytes.github.io/programming/android/kotlin/native/c/interop/interoperability/2022/09/10/Kotlin-Native-C-Interop.html flyingbytes.github.io/programming/android/kotlin/native/c/interop/interoperability/2022/09/10/Kotlin-Native-C-Interop.html programming android kotlin native C Programming Interop Interoperability Enable Kotlin Context Receivers in an Android Project <p>Hello everybody,</p> <p>As some of you know, <a href="https://blog.jetbrains.com/kotlin/2022/02/kotlin-1-6-20-m1-released/">Context Receivers</a> are a new, unstable feature added in Kotlin 1.6.20. I find them really interesting, as they are a syntactical generalization of extension functions (although extension functions and context receiver are used in different semantic cases, see <a href="https://www.youtube.com/watch?v=GISPalIVdQY">this video</a> for an explanation).</p> <p>As I went along trying out Context Receivers, I found it rather difficult to enable them for toying around. Unfortunately, I am missing the usual step-by-step tutorial by JetBrains. They only tell us that we have to <a href="https://github.com/Kotlin/KEEP/blob/master/proposals/context-receivers.md#prototype">add a compile flag</a>, but this does not help much. And most blog posts skip this step as well. Even Stack Overflow does not help this time! This blog post should help everyone who has the same problem enabling Context Receivers without wasting as much time as I did searching for the necessary actions.</p> <p>Of course, all of this could change dramatically when the feature becomes stable over time. This guide is from June 2022, and I use Android Studio Chipmunk as my IDE.</p> <h2 id="0-add-context-receiver-to-code">0. Add Context Receiver to Code</h2> <p>Before we enable Context Receivers, we add the following class somewhere in our app:</p> <div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nf">context</span><span class="p">(</span><span class="nc">Unit</span><span class="p">)</span> <span class="kd">class</span> <span class="nc">Test</span><span class="p">()</span> </code></pre></div></div> <p>To make this compile, we have to do the following two actions:</p> <h2 id="1-update-kotlin-language-features">1. Update Kotlin Language Features</h2> <p>To fix the “Expecting a top level declaration” compile error, first, we have to enable the language features of Kotlin 1.6.20 (or higher). We do this by updating the used Kotlin version inside the <code class="language-plaintext highlighter-rouge">build.gradle</code> file of the project folder:</p> <div class="language-groovy highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">plugins</span> <span class="o">{</span> <span class="o">...</span> <span class="n">id</span> <span class="s1">'org.jetbrains.kotlin.android'</span> <span class="n">version</span> <span class="s1">'1.6.20'</span> <span class="n">apply</span> <span class="kc">false</span> <span class="err">#</span><span class="n">Or</span> <span class="n">anything</span> <span class="n">higher</span> <span class="n">than</span> <span class="mf">1.7</span><span class="o">.</span><span class="mi">0</span> <span class="o">}</span> </code></pre></div></div> <p>This fixes the error.</p> <h2 id="2-enable-context-receivers">2. Enable Context Receivers</h2> <p>To fix the “The feature ‘context receivers’ is experimental and should be enabled explicitly” compile error, we have to set the following compile flag inside the <code class="language-plaintext highlighter-rouge">build.gradle</code> file of the <code class="language-plaintext highlighter-rouge">app</code> module folder:</p> <div class="language-groovy highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">android</span> <span class="o">{</span> <span class="n">kotlinOptions</span> <span class="o">{</span> <span class="o">...</span> <span class="n">freeCompilerArgs</span> <span class="o">+=</span> <span class="s2">"-Xcontext-receivers"</span> <span class="o">}</span> <span class="o">}</span> </code></pre></div></div> <p>Now, the code compiles. Congratulations!</p> <h2 id="conclusion">Conclusion</h2> <p>That’s it for today!</p> <p>You have seen the necessary steps to enable Context Receivers in any Android app.</p> <p>Unfortunately, Android Studio (Chipmunk) still shows a syntax error when using Context Receivers. However, the code still compiles and works. Do you know any way to remove this error? If so, please present it in the comment section below.</p> <p>Please leave a comment if this post helped you or if you have any questions regarding this blog post.</p> <p>Thanks for reading and have a nice day,</p> <p>Niklas</p> Mon, 13 Jun 2022 18:00:00 +0000 flyingbytes.github.io/programming/android/kotlin/context/receiver/contextreceiver/kotlin17/kotlin1620/2022/06/13/Enable-Context-Receiver-Android.html flyingbytes.github.io/programming/android/kotlin/context/receiver/contextreceiver/kotlin17/kotlin1620/2022/06/13/Enable-Context-Receiver-Android.html programming android kotlin context receiver contextreceiver kotlin17 kotlin1620 Setting up LibGDX, Kotlin and Admob (with Android) <p>Hello everybody,</p> <p>As regular readers of my blog know, I love <a href="https://flyingbytes.github.io/programming/java8/functional/part0/2017/01/16/Java8-Part0.html">functional programming</a>. And I love <a href="https://flyingbytes.github.io/programming/android/2017/11/06/Android-Ode.html">Android app programming</a>, and I hope you do too.<br /> While programming my latest Android game <a href="https://play.google.com/store/apps/details?id=de.nwuensche.jeweltrop&amp;hl=gsw">Jewel Trop</a>, I had several problems adding ads which I couldn’t solve immediately. For example, libGDX genereates <em>three</em> different <code class="language-plaintext highlighter-rouge">build.gradle</code> files, so good luck finding the right one for your dependencies.<br /> For some of these problems I couldn’t find direct help in the Internet, so I decided to share this step-by-step guide to walk you through all of solutions and save you some time.<br /> If you don’t care about the details and just about the code, then go straight to my <a href="https://github.com/NWuensche/AdsLibGDXKotlin">GitHub project</a> where I added all the code combined in an unchanged libGDX Project.</p> <p>Without further ado, let’s do this!</p> <h2 id="adding-android-admobfirebase-ads-dependency">Adding Android Admob/Firebase-Ads Dependency</h2> <p>To add support for Admob Ads in your app, open the <code class="language-plaintext highlighter-rouge">android/build.gradle</code> file (in your <code class="language-plaintext highlighter-rouge">android</code> folder) and add the following new dependency block at the very end of the file:</p> <pre> ... } eclipse.project.name = appName + "-android" <b>dependencies {</b> <b>implementation 'com.google.firebase:firebase-ads:19.0.1'</b> <b>}</b> </pre> <h2 id="enabling-android-x">Enabling Android X</h2> <p>After you try to compile your app now, an unpleasant error will be displayed:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>This project uses AndroidX dependencies, but the 'android.useAndroidX' property is not enabled. Set this property to true in the gradle.properties file and retry. The following AndroidX dependencies are detected: androidx.versionedparcelable:versionedparcelable:1.0.0, androidx.slidingpanelayout:slidingpanelayout:1.0.0, androidx.fragment:fragment:1.0.0, androidx.core:core:1.0.0, androidx.customview:customview:1.0.0, androidx.swiperefreshlayout:swiperefreshlayout:1.0.0, androidx.interpolator:interpolator:1.0.0, androidx.loader:loader:1.0.0, androidx.drawerlayout:drawerlayout:1.0.0, androidx.viewpager:viewpager:1.0.0, androidx.collection:collection:1.0.0, androidx.localbroadcastmanager:localbroadcastmanager:1.0.0, androidx.lifecycle:lifecycle-common:2.0.0, androidx.arch.core:core-common:2.0.0, androidx.annotation:annotation:1.0.0, androidx.legacy:legacy-support-core-ui:1.0.0, androidx.lifecycle:lifecycle-livedata:2.0.0, androidx.lifecycle:lifecycle-viewmodel:2.0.0, androidx.browser:browser:1.0.0, androidx.lifecycle:lifecycle-livedata-core:2.0.0, androidx.arch.core:core-runtime:2.0.0, androidx.legacy:legacy-support-core-utils:1.0.0, androidx.documentfile:documentfile:1.0.0, androidx.cursoradapter:cursoradapter:1.0.0, androidx.lifecycle:lifecycle-runtime:2.0.0, androidx.coordinatorlayout:coordinatorlayout:1.0.0, androidx.asynclayoutinflater:asynclayoutinflater:1.0.0, androidx.print:print:1.0.0 </code></pre></div></div> <p>To solve this issue, open the <code class="language-plaintext highlighter-rouge">gradle.properties</code> file in your root folder and add the following line to enable Android X:</p> <pre> org.gradle.daemon=true org.gradle.jvmargs=-Xms128m -Xmx1500m org.gradle.configureondemand=false <b>android.useAndroidX=true</b> </pre> <h3 id="adding-an-adview-to-your-project">Adding an AdView to your Project</h3> <p>Now you can add the Admob app ID in your <code class="language-plaintext highlighter-rouge">android/AndroidManifest.xml</code> file and an AdView to your <code class="language-plaintext highlighter-rouge">AndroidLauncher</code>. The minimal example for this is:</p> <p>android/AndroidManifest.xml:</p> <pre> &lt;/activity&gt; <b>&lt;meta-data</b> <b>android:name="com.google.android.gms.ads.APPLICATION_ID"</b> <b>android:value="ca-app-pub-3940256099942544~3347511713" /&gt;</b> &lt;/application&gt; &lt;/manifest&gt; </pre> <p>android/…/AndroidLauncher.java:</p> <pre> ... public class AndroidLauncher extends AndroidApplication { @Override protected void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); AndroidApplicationConfiguration config = new AndroidApplicationConfiguration(); <b>AdView a = new AdView(this);</b> initialize(new MyGdxGame(), config); } ... </pre> <h3 id="increase-minimum-android-sdk-version">Increase Minimum Android SDK Version</h3> <p>Compiling now gives you the following error message:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Manifest merger failed : uses-sdk:minSdkVersion 14 cannot be smaller than version 16 declared in library [com.google.firebase:firebase-ads:19.0.1] .../firebase-ads-19.0.1/AndroidManifest.xml as the library might be using APIs not available in 14 Suggestion: use a compatible library with a minSdk of at most 14, or increase this project's minSdk version to at least 16, or use tools:overrideLibrary="com.google.firebase.firebase_ads" to force usage (may lead to runtime failures) </code></pre></div></div> <p>So we need to increase the minimal Android Version 16 (Android 4.1 Jelly Bean). This can be done easily in the <code class="language-plaintext highlighter-rouge">android/build.gradle</code> file:</p> <pre> defaultConfig { applicationId "com.mygdx.game" <b>minSdkVersion 16</b> //From 14 targetSdkVersion 29 ... </pre> <p>If your app compiles without any errors by now, congratulations. But for all the developers who have errors while using other big dependencies other then Admob, don’t worry, I’ve got you covered with <em>multiple DEX files</em>.</p> <h2 id="too-many-classes--multidex">Too Many Classes / Multidex</h2> <p>The last problem on our journey is appears when we try to compile now:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Cannot fit requested classes in a single dex file (# methods: 93902 &gt; 65536) </code></pre></div></div> <p>With all of our dependencies (in my case the amazing functional programming library <a href="https://arrow-kt.io/">Arrow</a>) we just have too many classes in our app for <em>one</em> DEX file.</p> <p>The solution is to add support for multiple DEX files in our app. Therefore, we add and enable the multi dex dependency in our <code class="language-plaintext highlighter-rouge">android/build.gradle</code> file:</p> <pre> ... defaultConfig { applicationId "com.mygdx.game" minSdkVersion 16 targetSdkVersion 29 versionCode 1 versionName "1.0" <b>multiDexEnabled true</b> } ... </pre> <p>and</p> <pre> dependencies { implementation 'com.google.firebase:firebase-ads:19.0.1' <b>implementation 'com.android.support:multidex:1.0.3'</b> } </pre> <p>once re-compiled, we get the following (and last) error message:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>More than one file was found with OS independent path 'androidsupportmultidexversion.txt' </code></pre></div></div> <p>Because this txt file is there more than once, we have to exclude it in the <code class="language-plaintext highlighter-rouge">android/build.gradle</code> file:</p> <pre> ... packagingOptions { exclude 'META-INF/robovm/ios/robovm.xml' <b>exclude 'androidsupportmultidexversion.txt'</b> } ... </pre> <p>As you will notice, your app will now compile without any error and your good to go. Congratulations, you’ve done it!</p> <h2 id="conclusion">Conclusion</h2> <p>That’s it for today!</p> <p>We have fixed all nasty problems towards showing ads in your own libGDX game. We enabled Android X and manifest merging for the ad dependency and multiple DEX files for all our other dependencies.<br /> You can find all of the code combined in a vanilla libGDX Project on <a href="https://github.com/NWuensche/AdsLibGDXKotlin">GitHub</a>.</p> <p>From here on, you can follow the wonderful <a href="https://github.com/libgdx/libgdx/wiki/Admob-in-libgdx">guide by libGDX itself</a> on how to display ads in your app or the great <a href="https://medium.com/swlh/adding-admob-banner-and-interstitial-ads-to-your-android-app-step-by-step-from-scratch-8505d02a09d8#8d7a">guide by Cansu Yeksan Aktaş</a>.</p> <p>Please leave a comment if this post helped you or if you have any questions regarding this blog post.</p> <p>Thanks for reading and have a nice day,</p> <p>Niklas</p> Sun, 22 Mar 2020 19:00:00 +0000 flyingbytes.github.io/programming/android/functional/kotlin/libgdx/admob/2020/03/22/LibGDX-Kotlin-Admob.html flyingbytes.github.io/programming/android/functional/kotlin/libgdx/admob/2020/03/22/LibGDX-Kotlin-Admob.html programming android functional kotlin libgdx admob Learn IntelliJ Shortcuts with the IntelliJTutor <p>Whether it is CLion, PyCharm or IntelliJ, many people use some Jetbrain IDE in their daily life. These IDEs have many great features, work on all distributions and just make your work easier. However, most people don’t use the full potential these programs allow. Many developers don’t use any shortcuts at all, but just use their mouse or touchpad to click buttons inside the IDE.</p> <p>In my eyes, that’s a real bummer. You can get much more done by using some shortcuts in your day to day work. Moving your fingers to your pointing device just slows you down. Keeping your hands on the keyboard and pressing shortcuts is much faster and more precise than moving the cursor on the screen.</p> <p>To help you getting started with shortcuts, I created a project called IntelliJTutor. The tutorial is very self explanatory and you shouldn’t have any problem using it. Nevertheless, if you have any concerns with it, just create an issue or pull request on GitHub or write a command below this post.</p> <p>The name and the project are an homage to the Vimtutor. When I started learning Vim with all of it shortcuts, it was so great to have the Vimtutor to guide me through the most basic commands to control Vim.</p> <p>As I have to work a lot with IntelliJ and Android Studio these days, I thought it would be nice to have a tutor for these IDEs too. The shortcuts I mention in the tutorial work for WebStorm, CLion and all the other Jetbrain IDEs as well.</p> <p>If you want to take a look at the tutor, you can find it <a href="https://github.com/NWuensche/IntelliJTutor">here</a>.</p> <p>What do you think about this project? Is it a good start for learning shortcuts or do you find it frustrating? Please share your opinion in the comment section.</p> <p>Thank you for reading and have a nice day,</p> <p>Niklas</p> Fri, 06 Apr 2018 12:00:00 +0000 flyingbytes.github.io/programming/intellij/training/2018/04/06/IntelliJTutor.html flyingbytes.github.io/programming/intellij/training/2018/04/06/IntelliJTutor.html programming intellij training How to Set Up Wallabag on Uberspace <p>Today, I want to show you how to set up your own Wallabag instance on an Uberspace server.</p> <h2 id="set-up-composer">Set Up Composer</h2> <p>First of all, we will need Composer for using Wallabag. You can find the guide I used for this <a href="https://getcomposer.org/download/">here</a>:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>mkdir /var/www/virtual/$USER/wallabag cd /var/www/virtual/$USER/wallabag php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" php -r "if (hash_file('SHA384', 'composer-setup.php') === '544e09ee996cdf60ece3804abc52599c22b1f40f4323403c44d44fdfdd586475ca9813a858088ffbc1f233e9b180f061') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;" php composer-setup.php php -r "unlink('composer-setup.php');" </code></pre></div></div> <h2 id="set-up-wallabag">Set Up Wallabag</h2> <p>We will use <a href="https://doc.wallabag.org/en/admin/installation/installation.html">this</a> guide for installing Wallabag on our server. For that, let’s concentrate on the shared hosting part here:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>wget https://wllbg.org/latest-v2-package &amp;&amp; tar xvf latest-v2-package -C /var/www/virtual/$USER/wallabag --strip-components=1 cd /var/www/virtual/$USER/wallabag php bin/console wallabag:install --env=prod #Remember the username + password </code></pre></div></div> <p>You can shut down this Wallabag instance, because it uses port 8000, which Uberspace doesn’t open for the outside world.</p> <h2 id="adapt-wallabag-for-uberspace">Adapt Wallabag for Uberspace</h2> <p>Now, we’re going to set up our domain and after that, we want to start Wallabag, but with a different port:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>uberspace-add-domain -d "*.$USER.$HOSTNAME" -w uberspace-add-port -p both -f #Remember the number of the port. php bin/console server:start 0.0.0.0:PORTNUMBER -e prod </code></pre></div></div> <p>Finally, you have access to your Wallabag server from anywhere under <code class="language-plaintext highlighter-rouge">$USER.$HOSTNAME:PORTNUMBER</code>. You can login with the username and password you used when you set up Wallabag (default is Wallabag/Wallabag).</p> <p>Thanks for reading and have a nice day, please leave some feedback too!</p> <p>Niklas</p> Sat, 11 Nov 2017 12:00:00 +0000 flyingbytes.github.io/wallabag/uberspace/2017/11/11/Wallabag-Uberspace.html flyingbytes.github.io/wallabag/uberspace/2017/11/11/Wallabag-Uberspace.html Wallabag Uberspace An Ode to Android <p>Let’s face it: I’m an Android fanboy.</p> <p>The Android Platform is one of my favorite, if not my most favorite, platform to develop for.</p> <p>I want to tell you exactly why I think Google makes a good job regarding Android. Nevertheless, I also try to highlight some problems I have with Android, because be realistic: Nothing’s perfect.</p> <h2 id="the-development-environment">The Development Environment</h2> <p>Back in the days, Android Development in Eclipse was such a paint. The IDE just wasn’t meant to be used for job of developing apps. Plugin Management was painful, the UI preview didn’t really work and everything crashed most of the time (at least for me).</p> <p>However, Android Studio was developed to solve these problems. And it does so to an almost perfect degree. You can tell that Google keeps an eye on feedback and integrates every new tool nicely into the IDE (Kotlin, Espresso Test Recorder, …). The development of the app’s UI is just as fast and smooth as the creation of business logic. It just feels right doing all of this. Developing Android Apps is such a pleasure nowadays.</p> <h2 id="the-language">The Language</h2> <p>I like Java very much. In my opinion, static typing makes much more sense in big applications than dynamic typing. But I also like the design decisions behind the syntax. The functional programming techniques, which were introduced in Java 8, are also implemented nicely into Java’s ecosystem. If you want to learn more about them, check out my <a href="https://flyingbytes.github.io/programming/java8/functional/part0/2017/01/16/Java8-Part0.html">other posts</a>.</p> <p>Every time I read or work with Android Code, the language doesn’t get in my way. It just makes sense and is easy to understand.</p> <h2 id="the-bug-bounty-system">The Bug Bounty System</h2> <p>Breaking other peoples code is a real pleasure for me ;) . Getting inside a developer’s mind and exploiting common code habits can can keep me busy for a whole weekend. And <a href="https://medium.freecodecamp.org/messing-with-the-google-buganizer-system-for-15-600-in-bounties-58f86cc9f9a5">bug bounty reports</a> are by far the most fascinating blog posts for me.</p> <p>However, this task is even more rewarding now, because Google expanded it’s <a href="https://www.google.com/about/appsecurity/android-rewards/">bug bounty program</a> onto some Android Apps last month. Now, you can make real money reporting issues you found and learn so much about the Android system while searching bugs.</p> <h2 id="the-testing-environment">The Testing Environment</h2> <p>As a developer who cares a lot about testing, I want to make sure that every released app of mine works as intended. I don’t want to release buggy software. Android makes it so easy to do achieve this goal. Espresso and Robolectric are so intuitive and they just <strong>work</strong>. And if you also use Kotlin in your projects, it’s easy to make your tests even more readable with extension functions.</p> <p>It just feels right to write tests. This is so important in an environment where few people practice TDD and just rely on luck to find bugs.</p> <h2 id="contributing">Contributing</h2> <p>When I’m working on a new project, it’s always easy to get started. The amazing work Google does at documenting Android features is one of the best reasons for that.</p> <p>What’s more, every time I have a problem, there is someone in an IRC chat or part of an email list who can give me a quick answer. When I develop for other platforms, I haven’t felt this invited in their communities.</p> <hr /> <p>But of course, not everything’s good about Android. There are still problems that this platform has and which simply annoy me as a developer.</p> <h2 id="new-year--new-android-version">New year = New Android Version</h2> <p>Let’s be clear: It’s awesome when a platform develops over time. But maybe Google should give us the time to really embrace new features.</p> <p>Not even a <a href="https://www.statista.com/statistics/271774/share-of-android-platforms-on-mobile-devices-with-android-os/">quarter</a> of the Android users use Android N at this time. Still, there is Oreo coming out right now.</p> <p>However, you can’t use all of the new features and upgrade the minimum SDK Version of your app. This is because most of the users don’t buy a new phone with the latest Android version every year. Also, phone manufactures usually don’t provide new Android versions for their older phones. And not everybody wants to use a custom OS on their device.</p> <p>Google should just give the developers and users more time to adapt to a new Android Version.</p> <h2 id="conclusion">Conclusion</h2> <p>To sum everything up: The Android platform is an superb platform for developers. Google provides an awesome IDE and documentation which doesn’t leave anyone behind. The community is amazing as well.</p> <p>Still, the system’s not perfect. Google should slow down the release cycle so that the developers and users can adapt better to every new Android version.</p> <p>What’s your opinion on all of this? Which parts of the Android ecosystem do you love or hate? Please write a comment and check out my other blog posts too!</p> <p>Thanks for reading and have a nice day,</p> <p>Niklas</p> Mon, 06 Nov 2017 12:00:00 +0000 flyingbytes.github.io/programming/android/2017/11/06/Android-Ode.html flyingbytes.github.io/programming/android/2017/11/06/Android-Ode.html programming android An Introduction to Functional Programming in Java 8: Part 4 - Splitter <p>Hello everybody,</p> <p>In the <a href="https://flyingbytes.github.io/programming/java8/functional/part3/2017/02/18/Java8-Part3.html">last parts</a>, we’ve learned about the most basic ways to program functional in Java. We used functions as Objects, Streams and so much more.</p> <p>Today, we want to create a useful example with them. You will train the paradigms of the last parts and learn how the optimize the run time of your program.</p> <h2 id="example-split-a-stream-by-a-specific-filter">Example: Split a Stream by a specific filter</h2> <p>You might have stumbled over a problem like this before: You have a collection of objects and want to split them by a specific filter. After that, you want to perform some action with all elements who passed the test and another action with the ones that didn’t passed the test.</p> <h3 id="the-basic-and-slow-approach">The Basic (and Slow) Approach</h3> <figure class="highlight"><pre><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="o">&lt;</span><span class="no">T</span><span class="o">&gt;</span> <span class="kt">void</span> <span class="nf">splitAndPerform</span><span class="o">(</span><span class="nc">Collection</span><span class="o">&lt;</span><span class="no">T</span><span class="o">&gt;</span> <span class="n">items</span><span class="o">,</span> <span class="nc">Predicate</span><span class="o">&lt;</span><span class="no">T</span><span class="o">&gt;</span> <span class="n">splitBy</span><span class="o">,</span> <span class="nc">Consumer</span><span class="o">&lt;</span><span class="no">T</span><span class="o">&gt;</span> <span class="n">passed</span><span class="o">,</span> <span class="nc">Consumer</span><span class="o">&lt;</span><span class="no">T</span><span class="o">&gt;</span> <span class="n">notPassed</span><span class="o">)</span> <span class="o">{</span> <span class="n">items</span><span class="o">.</span><span class="na">stream</span><span class="o">()</span> <span class="o">.</span><span class="na">filter</span><span class="o">(</span><span class="n">splitBy</span><span class="o">)</span> <span class="o">.</span><span class="na">forEach</span><span class="o">(</span><span class="n">passed</span><span class="o">);</span> <span class="n">items</span><span class="o">.</span><span class="na">stream</span><span class="o">()</span> <span class="o">.</span><span class="na">filter</span><span class="o">(</span><span class="n">splitBy</span><span class="o">.</span><span class="na">negate</span><span class="o">())</span> <span class="o">.</span><span class="na">forEach</span><span class="o">(</span><span class="n">notPassed</span><span class="o">);</span> <span class="o">}</span></code></pre></figure> <p>This approach works, but it is pretty slow. The run time for splitting alone is O(2n), because we go through the whole collection 2 times: Ones to get all the items that passed the test and ones to get all the items that didn’t passed it.</p> <p>But what if we would create a splitter on our own? It’d sort all items in the collection, depending on whether or not they pass the test, into one List or the other. This would lower the run time to split the collection to O(n), because you just have to call filter once, not twice.</p> <p>So let’s do this.</p> <h2 id="the-better-approach">The Better Approach</h2> <h3 id="1-split-the-collection">1. Split the Collection</h3> <p>The first step to building our splitter is to, you guessed it, split it.</p> <p>In our <code class="language-plaintext highlighter-rouge">splitBy()</code> function, we want to take a <code class="language-plaintext highlighter-rouge">Predeciate&lt;T&gt;</code> as a parameter and return a new <code class="language-plaintext highlighter-rouge">Splitter</code> object, which is basically an object which consists of two Lists. One List consists of all the objects that passed the test, and the other one of all the objects that didn’t pass the test.</p> <figure class="highlight"><pre><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">Splitter</span><span class="o">&lt;</span><span class="no">T</span><span class="o">&gt;</span> <span class="o">{</span> <span class="kd">private</span> <span class="nc">List</span><span class="o">&lt;</span><span class="no">T</span><span class="o">&gt;</span> <span class="n">passed</span><span class="o">;</span> <span class="kd">private</span> <span class="nc">List</span><span class="o">&lt;</span><span class="no">T</span><span class="o">&gt;</span> <span class="n">notPassed</span><span class="o">;</span> <span class="kd">private</span> <span class="nf">Splitter</span><span class="o">(</span><span class="nc">List</span><span class="o">&lt;</span><span class="no">T</span><span class="o">&gt;</span> <span class="n">passed</span><span class="o">,</span> <span class="nc">List</span><span class="o">&lt;</span><span class="no">T</span><span class="o">&gt;</span> <span class="n">notPassed</span><span class="o">)</span> <span class="o">{</span> <span class="k">this</span><span class="o">.</span><span class="na">passed</span> <span class="o">=</span> <span class="n">passed</span><span class="o">;</span> <span class="k">this</span><span class="o">.</span><span class="na">notPassed</span> <span class="o">=</span> <span class="n">notPassed</span><span class="o">;</span> <span class="o">}</span> <span class="kd">public</span> <span class="kd">static</span> <span class="o">&lt;</span><span class="no">T</span><span class="o">&gt;</span> <span class="nc">Splitter</span><span class="o">&lt;</span><span class="no">T</span><span class="o">&gt;</span> <span class="nf">splitBy</span><span class="o">(</span><span class="nc">Collection</span><span class="o">&lt;</span><span class="no">T</span><span class="o">&gt;</span> <span class="n">items</span><span class="o">,</span><span class="nc">Predicate</span><span class="o">&lt;</span><span class="no">T</span><span class="o">&gt;</span> <span class="n">test</span><span class="o">)</span> <span class="o">{</span> <span class="nc">List</span><span class="o">&lt;</span><span class="no">T</span><span class="o">&gt;</span> <span class="n">passed</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">LinkedList</span><span class="o">&lt;</span><span class="no">T</span><span class="o">&gt;();</span> <span class="nc">List</span><span class="o">&lt;</span><span class="no">T</span><span class="o">&gt;</span> <span class="n">notPassed</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">LinkedList</span><span class="o">&lt;</span><span class="no">T</span><span class="o">&gt;();</span> <span class="n">items</span><span class="o">.</span><span class="na">stream</span><span class="o">()</span> <span class="o">.</span><span class="na">forEach</span><span class="o">(</span><span class="n">item</span> <span class="o">-&gt;</span> <span class="o">{</span> <span class="k">if</span><span class="o">(</span><span class="n">test</span><span class="o">.</span><span class="na">test</span><span class="o">(</span><span class="n">item</span><span class="o">)){</span> <span class="n">passed</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">item</span><span class="o">);</span> <span class="k">return</span><span class="o">;</span> <span class="o">}</span> <span class="n">notPassed</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">item</span><span class="o">);</span> <span class="o">});</span> <span class="k">return</span> <span class="k">new</span> <span class="nc">Splitter</span><span class="o">&lt;</span><span class="no">T</span><span class="o">&gt;(</span><span class="n">passed</span><span class="o">,</span> <span class="n">notPassed</span><span class="o">);</span> <span class="o">}</span> <span class="o">}</span></code></pre></figure> <p>As you can see, we used the factory method pattern to make the creation of the Splitter nicer.</p> <p>Now that we can create a Splitter object, we want to give it some functionality.</p> <h3 id="2-work-with-the-split-lists">2. Work With the Split Lists</h3> <p>We want to work with the Lists in the same way that we can work with Streams. But we don’t want to recreate every function that a Stream has for our two lists. That’s where a nice design pattern comes in handy. I heard about it in this <a href="https://youtu.be/e4MT_OguDKg?t=45m30">talk</a> and it’s a very cool way to use lambdas. We basically create two new functions, called <code class="language-plaintext highlighter-rouge">workOnPassedItems</code> and <code class="language-plaintext highlighter-rouge">workOnNotPassedItems</code>. They take a <code class="language-plaintext highlighter-rouge">Consumer&lt;Stream&lt;T&gt;&gt;</code>. Therefore, we can create a lambda and work inside it with a normal looking stream. This method will then be applied onto the List of passed and not passed items.</p> <figure class="highlight"><pre><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">Splitter</span><span class="o">&lt;</span><span class="no">T</span><span class="o">&gt;</span> <span class="o">{</span> <span class="c1">//...</span> <span class="kd">public</span> <span class="nc">Splitter</span><span class="o">&lt;</span><span class="no">T</span><span class="o">&gt;</span> <span class="nf">workWithPassed</span><span class="o">(</span><span class="nc">Consumer</span><span class="o">&lt;</span><span class="nc">Stream</span><span class="o">&lt;</span><span class="no">T</span><span class="o">&gt;&gt;</span> <span class="n">func</span><span class="o">)</span> <span class="o">{</span> <span class="n">func</span><span class="o">.</span><span class="na">accept</span><span class="o">(</span><span class="n">passed</span><span class="o">.</span><span class="na">stream</span><span class="o">());</span> <span class="k">return</span> <span class="k">this</span><span class="o">;</span> <span class="o">}</span> <span class="kd">public</span> <span class="nc">Splitter</span><span class="o">&lt;</span><span class="no">T</span><span class="o">&gt;</span> <span class="nf">workWithNotPassed</span><span class="o">(</span><span class="nc">Consumer</span><span class="o">&lt;</span><span class="nc">Stream</span><span class="o">&lt;</span><span class="no">T</span><span class="o">&gt;&gt;</span> <span class="n">func</span><span class="o">)</span> <span class="o">{</span> <span class="n">func</span><span class="o">.</span><span class="na">accept</span><span class="o">(</span><span class="n">notPassed</span><span class="o">.</span><span class="na">stream</span><span class="o">());</span> <span class="k">return</span> <span class="k">this</span><span class="o">;</span> <span class="o">}</span> <span class="o">}</span></code></pre></figure> <p>We used the cascade design pattern to make the use of multiple methods nicer. You will see it in the example down below.</p> <p>And that’s basically our Splitter! Now, we can try out some examples on how to use it.</p> <h3 id="example-1-showing-numbers-but-squaring-all-odd-numbers">Example 1: Showing numbers, but squaring all odd numbers</h3> <p>In this very first example we want to operate over a list of numbers. For each even number, we just want to print this number out. But for every odd number, we want to square them before we print them out.</p> <p>So first off, we want to split the list into even and odd numbers. After that, we can work on the lists as already told.</p> <figure class="highlight"><pre><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kt">void</span> <span class="nf">workOnNumbers</span><span class="o">()</span> <span class="o">{</span> <span class="nc">List</span><span class="o">&lt;</span><span class="nc">Integer</span><span class="o">&gt;</span> <span class="n">numbers</span> <span class="o">=</span> <span class="nc">Arrays</span><span class="o">.</span><span class="na">asList</span><span class="o">(</span><span class="mi">1</span><span class="o">,</span> <span class="mi">2</span><span class="o">,</span> <span class="mi">3</span><span class="o">,</span> <span class="mi">4</span><span class="o">,</span> <span class="mi">5</span><span class="o">,</span> <span class="mi">6</span><span class="o">,</span> <span class="mi">7</span><span class="o">,</span> <span class="mi">8</span><span class="o">,</span> <span class="mi">9</span><span class="o">,</span> <span class="mi">10</span><span class="o">);</span> <span class="nc">Splitter</span><span class="o">.</span><span class="na">splitBy</span><span class="o">(</span><span class="n">numbers</span><span class="o">,</span> <span class="n">num</span> <span class="o">-&gt;</span> <span class="n">num</span><span class="o">%</span><span class="mi">2</span> <span class="o">==</span> <span class="mi">0</span><span class="o">)</span> <span class="o">.</span><span class="na">workWithPassed</span><span class="o">(</span><span class="n">passed</span> <span class="o">-&gt;</span> <span class="n">passed</span><span class="o">.</span><span class="na">forEach</span><span class="o">(</span><span class="n">even</span> <span class="o">-&gt;</span> <span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">""</span> <span class="o">+</span> <span class="n">even</span> <span class="o">+</span> <span class="s">" -&gt; "</span> <span class="o">+</span> <span class="n">even</span><span class="o">)))</span> <span class="o">.</span><span class="na">workWithNotPassed</span><span class="o">(</span><span class="n">notPassed</span> <span class="o">-&gt;</span> <span class="n">notPassed</span><span class="o">.</span><span class="na">map</span><span class="o">(</span><span class="n">odd</span> <span class="o">-&gt;</span> <span class="n">odd</span> <span class="o">*</span> <span class="n">odd</span><span class="o">)</span> <span class="o">.</span><span class="na">forEach</span><span class="o">(</span><span class="n">odd</span> <span class="o">-&gt;</span> <span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">""</span> <span class="o">+</span> <span class="nc">Math</span><span class="o">.</span><span class="na">sqrt</span><span class="o">(</span><span class="n">odd</span><span class="o">)</span> <span class="o">+</span> <span class="s">" -&gt; "</span> <span class="o">+</span> <span class="n">odd</span><span class="o">)</span> <span class="o">));</span> <span class="o">}</span></code></pre></figure> <h3 id="example-2-sending-all-winners-a-confirmation-and-all-losers-a-cancellation">Example 2: Sending all Winners a Confirmation and all Losers a Cancellation</h3> <p>Now, we have a List of <code class="language-plaintext highlighter-rouge">Candidates</code>. All of these people have a method called <code class="language-plaintext highlighter-rouge">hasWon()</code>, which gives back a boolean. We want to split the List into Winners and Losers. After that, we want to send all Winners a confirmation that they won, and all losers a cancellation that they lost. So let’s do this!</p> <figure class="highlight"><pre><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kt">void</span> <span class="nf">sendEmails</span><span class="o">(</span><span class="nc">List</span><span class="o">&lt;</span><span class="nc">Candidates</span><span class="o">&gt;</span> <span class="n">candidates</span><span class="o">)</span> <span class="o">{</span> <span class="nc">Splitter</span><span class="o">.</span><span class="na">splitBy</span><span class="o">(</span><span class="n">candidates</span><span class="o">,</span> <span class="nl">Candidates:</span><span class="o">:</span><span class="n">hasWon</span><span class="o">)</span> <span class="o">.</span><span class="na">workWithPassed</span><span class="o">(</span><span class="n">winners</span> <span class="o">-&gt;</span> <span class="n">winners</span><span class="o">.</span><span class="na">forEach</span><span class="o">(</span><span class="n">winner</span> <span class="o">-&gt;</span> <span class="nc">Email</span><span class="o">.</span><span class="na">send</span><span class="o">(</span><span class="n">winner</span><span class="o">.</span><span class="na">getEmail</span><span class="o">(),</span> <span class="s">"You won!"</span><span class="o">))</span> <span class="o">)</span> <span class="o">.</span><span class="na">workWithNotPassed</span><span class="o">(</span><span class="n">losers</span> <span class="o">-&gt;</span> <span class="n">losers</span><span class="o">.</span><span class="na">forEach</span><span class="o">(</span><span class="n">loser</span> <span class="o">-&gt;</span> <span class="nc">Email</span><span class="o">.</span><span class="na">send</span><span class="o">(</span><span class="n">loser</span><span class="o">.</span><span class="na">getEmail</span><span class="o">(),</span> <span class="s">"You lost, sorry!"</span><span class="o">))</span> <span class="o">);</span> <span class="o">}</span></code></pre></figure> <h2 id="update-on-using-partitioningby">Update: On Using partitioningBy</h2> <p>After the post’s out for a day now, a lot of you have given feedback. And I really appreciate it! You told me about ways to make the Splitter class better.</p> <p>One of the discussed things is the use of <code class="language-plaintext highlighter-rouge">Stream.collect(Collectors.partitioningBy(Predicate&lt;T&gt; test))</code>. And I totally agree that it could be useful in our scenario.</p> <p>It partitions the Stream depending on a test function. So for us, the map would look something like this: <code class="language-plaintext highlighter-rouge">{true: passed, false: notPassed}</code>. After that, we just take the two lists out of the map and go on.</p> <p>So as <code class="language-plaintext highlighter-rouge">Philboyd_Studge</code> mentioned on Reddit, the new <code class="language-plaintext highlighter-rouge">splitBy</code> method could look something like this:</p> <figure class="highlight"><pre><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="o">&lt;</span><span class="no">T</span><span class="o">&gt;</span> <span class="nc">Splitter</span><span class="o">&lt;</span><span class="no">T</span><span class="o">&gt;</span> <span class="nf">splitBy</span><span class="o">(</span><span class="nc">Collection</span><span class="o">&lt;</span><span class="no">T</span><span class="o">&gt;</span> <span class="n">items</span><span class="o">,</span><span class="nc">Predicate</span><span class="o">&lt;</span><span class="no">T</span><span class="o">&gt;</span> <span class="n">test</span><span class="o">)</span> <span class="o">{</span> <span class="nc">Map</span><span class="o">&lt;</span><span class="nc">Boolean</span><span class="o">,</span> <span class="nc">List</span><span class="o">&lt;</span><span class="no">T</span><span class="o">&gt;&gt;</span> <span class="n">map</span> <span class="o">=</span> <span class="n">items</span><span class="o">.</span><span class="na">stream</span><span class="o">()</span> <span class="o">.</span><span class="na">collect</span><span class="o">(</span><span class="nc">Collectors</span><span class="o">.</span><span class="na">partitioningBy</span><span class="o">(</span><span class="n">test</span><span class="o">));</span> <span class="k">return</span> <span class="k">new</span> <span class="nc">Splitter</span><span class="o">&lt;</span><span class="no">T</span><span class="o">&gt;(</span><span class="n">map</span><span class="o">.</span><span class="na">get</span><span class="o">(</span><span class="kc">true</span><span class="o">),</span> <span class="n">map</span><span class="o">.</span><span class="na">get</span><span class="o">(</span><span class="kc">false</span><span class="o">));</span> <span class="o">}</span></code></pre></figure> <p>And I have to admit that this takes out a lot of noise. It just looks nicer than the <code class="language-plaintext highlighter-rouge">splitBy</code> method above. So thank you for that!</p> <h3 id="so-whats-the-splitters-right-to-exist">So what’s the Splitter’s Right to Exist?</h3> <p>The Splitter’s purpose is to demonstrate how you can work with functions as objects. Its purpose is <em>not</em> to replace some methods in the JDK.</p> <p>It’s a class for learning and playing around. If you want to tweak around, just do it. Please leave a comment on what you have learned or where you have optimized the class, so that others can learn from it too.</p> <p>In addition, we learned about design patterns. Some of you even told me that they learned new design patterns in this blog post.</p> <p>The patterns help to make the syntax nicer. When you split your collection in two parts, it’s nicer to use the cascade pattern in the Splitter than to handle a Map.</p> <h2 id="conclusion">Conclusion</h2> <p>That’s it for today!</p> <p>We have learned how to create our first useful class with the help of Streams. We also optimized the run time of our program with it. Therefore, we have trained our knowledge about design patterns like the factory method and the cascade pattern.</p> <p>Lastly, we have tried out our splitter with some examples.</p> <p>Next time, we will talk about RxJava. It’s a framework that uses the observer pattern for asynchronous tasks and builds upon functional programming.</p> <p>Are there any things that your splitter should do too? Please let me know in the comments. I’d love to hear your feedback too!</p> <p>Thanks for reading and have a nice day,</p> <p>Niklas</p> Fri, 10 Mar 2017 12:00:00 +0000 flyingbytes.github.io/programming/java8/functional/part4/2017/03/10/Java8-Part4.html flyingbytes.github.io/programming/java8/functional/part4/2017/03/10/Java8-Part4.html programming java8 functional part4 An Introduction to Functional Programming in Java 8: Part 3 - Streams <p>Hello everybody,</p> <p>In the <a href="https://flyingbytes.github.io/programming/java8/functional/part2/2017/02/04/Java8-Part2.html">last part</a>, we’ve learned about the Optional type and how to use it correctly.</p> <p>Today, we will learn about <code class="language-plaintext highlighter-rouge">Streams</code>, which you use as an functional alternative of working with Collections. Some method were already seen when we used Optionals, so be sure to check out <a href="https://flyingbytes.github.io/programming/java8/functional/part2/2017/02/04/Java8-Part2.html">the part about Optionals</a>.</p> <h2 id="where-do-we-use-streams">Where do we use Streams?</h2> <p>You might ask what’s wrong with the current way to store multiple objects? Why shouldn’t you use Lists, Sets and so on anymore?</p> <p>I want to point out: Nothing is wrong with them. But when you want to work functional (what you hopefully want after the last parts of this blog), you should consider using them. The standard workflow is to convert your data structure into a Stream. Then you want to work on them in a functional manner and in the end, you transform them back into the data structure of your choice.</p> <p>And that’s the reason we will learn to transform the most common data structures into streams.</p> <h2 id="why-do-we-use-streams">Why do we use Streams?</h2> <p>Streams are a wonderful new way to work with data collections. They were introduced in Java 8. One of the many reasons you should use them is the <em>Cascade</em> pattern that Streams use. This basically means that almost every Stream method returns the Stream again, so you can continue to work with it. In the next sections, you will see how this works and that it makes the code nicer.</p> <p>Streams are also immutable. So every time you manipulate it, you create a new Stream.</p> <p>Another nice thing about them is that they respect the properties of <em>fP</em>. If you convert a Data Structure into a Stream and work on it, the original data structure won’t be changed. So no side effects here!</p> <h2 id="how-to-convert-data-structures-into-streams">How to Convert Data Structures into Streams</h2> <h3 id="convert-multiple-objects-into-a-stream">Convert Multiple Objects into a Stream</h3> <p>If you want to make a Stream out of some objects, you can use the method <code class="language-plaintext highlighter-rouge">Stream.of()</code></p> <figure class="highlight"><pre><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kt">void</span> <span class="nf">convertObjects</span><span class="o">()</span> <span class="o">{</span> <span class="nc">Stream</span><span class="o">&lt;</span><span class="nc">String</span><span class="o">&gt;</span> <span class="n">objectStream</span> <span class="o">=</span> <span class="nc">Stream</span><span class="o">.</span><span class="na">of</span><span class="o">(</span><span class="s">"Hello"</span><span class="o">,</span> <span class="s">"World"</span><span class="o">);</span> <span class="o">}</span></code></pre></figure> <h3 id="converting-collections-lists-sets--and-arrays">Converting Collections (Lists, Sets, …) and Arrays</h3> <p>Luckily, Oracle has thought through the implementation of Streams in Java 8. Every Class that implements <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html">java.util.Collection&lt;T&gt;</a> has a new method called <code class="language-plaintext highlighter-rouge">stream()</code> which converts the collection into a Stream. Also Arrays can be converted easily with <code class="language-plaintext highlighter-rouge">Arrays.stream(array)</code>. It’s as easy as it get’s.</p> <figure class="highlight"><pre><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kt">void</span> <span class="nf">convertStuff</span><span class="o">()</span> <span class="o">{</span> <span class="nc">String</span><span class="o">[]</span> <span class="n">array</span> <span class="o">=</span> <span class="o">{</span><span class="s">"apple"</span><span class="o">,</span> <span class="s">"banana"</span><span class="o">};</span> <span class="nc">Set</span><span class="o">&lt;</span><span class="nc">String</span><span class="o">&gt;</span> <span class="n">emptySet</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">HashSet</span><span class="o">&lt;&gt;();</span> <span class="nc">List</span><span class="o">&lt;</span><span class="nc">Integer</span><span class="o">&gt;</span> <span class="n">emptyList</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">LinkedList</span><span class="o">&lt;&gt;();</span> <span class="nc">Stream</span><span class="o">&lt;</span><span class="nc">String</span><span class="o">&gt;</span> <span class="n">arrayStream</span> <span class="o">=</span> <span class="nc">Arrays</span><span class="o">.</span><span class="na">stream</span><span class="o">(</span><span class="n">array</span><span class="o">);</span> <span class="nc">Stream</span><span class="o">&lt;</span><span class="nc">String</span><span class="o">&gt;</span> <span class="n">setStream</span> <span class="o">=</span> <span class="n">emptySet</span><span class="o">.</span><span class="na">stream</span><span class="o">();</span> <span class="nc">Stream</span><span class="o">&lt;</span><span class="nc">Integer</span><span class="o">&gt;</span> <span class="n">listStream</span> <span class="o">=</span> <span class="n">emptyList</span><span class="o">.</span><span class="na">stream</span><span class="o">();</span> <span class="o">}</span></code></pre></figure> <p>However, normally you won’t store a Stream in an object. You just work with them and convert them back into your desired data structure.</p> <h2 id="working-with-streams">Working with Streams</h2> <p>As I already said, Streams are the way to work with data structures functional. And now we will learn about the most common methods to use.</p> <p>As a side note: In the next sections, I will use <code class="language-plaintext highlighter-rouge">T</code> as the type of the objects in the Stream.</p> <h3 id="methods-we-already-know">Methods we already know</h3> <p>You can use some methods we already heard about when we learned about Optionals also with Streams.</p> <h4 id="map">map</h4> <p>This works pretty straight forward. Instead of manipulating one item, which might be in the Optional, we manipulate all items in a stream. So if you have a function that squares a number, you can use map to use this function over multiple numbers without writing a new function for lists.</p> <figure class="highlight"><pre><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kt">void</span> <span class="nf">showMap</span><span class="o">()</span> <span class="o">{</span> <span class="nc">Stream</span><span class="o">.</span><span class="na">of</span><span class="o">(</span><span class="mi">1</span><span class="o">,</span> <span class="mi">2</span><span class="o">,</span> <span class="mi">3</span><span class="o">)</span> <span class="o">.</span><span class="na">map</span><span class="o">(</span><span class="n">num</span> <span class="o">-&gt;</span> <span class="n">num</span> <span class="o">*</span> <span class="n">num</span><span class="o">)</span> <span class="o">.</span><span class="na">forEach</span><span class="o">(</span><span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">::</span><span class="n">println</span><span class="o">);</span> <span class="c1">// 1 4 9</span> <span class="o">}</span></code></pre></figure> <h4 id="flatmap">flatMap</h4> <p>Like with Optionals, we use flatMap to going e.g from a Stream&lt;List&lt;Integer&gt;&gt; to Stream&lt;Integer&gt;. If you want to know more about look into <a href="https://flyingbytes.github.io/programming/java8/functional/part2/2017/02/04/Java8-Part2.html">part 2</a>.</p> <p>Here, we want to concat multiple Lists into one big List.</p> <figure class="highlight"><pre><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kt">void</span> <span class="nf">showFlatMapLists</span><span class="o">()</span> <span class="o">{</span> <span class="nc">List</span><span class="o">&lt;</span><span class="nc">Integer</span><span class="o">&gt;</span> <span class="n">numbers1</span> <span class="o">=</span> <span class="nc">Arrays</span><span class="o">.</span><span class="na">asList</span><span class="o">(</span><span class="mi">1</span><span class="o">,</span> <span class="mi">2</span><span class="o">,</span> <span class="mi">3</span><span class="o">);</span> <span class="nc">List</span><span class="o">&lt;</span><span class="nc">Integer</span><span class="o">&gt;</span> <span class="n">numbers2</span> <span class="o">=</span> <span class="nc">Arrays</span><span class="o">.</span><span class="na">asList</span><span class="o">(</span><span class="mi">4</span><span class="o">,</span> <span class="mi">5</span><span class="o">,</span> <span class="mi">6</span><span class="o">);</span> <span class="nc">Stream</span><span class="o">.</span><span class="na">of</span><span class="o">(</span><span class="n">numbers1</span><span class="o">,</span> <span class="n">numbers2</span><span class="o">)</span> <span class="c1">//Stream&lt;List&lt;Integer&gt;&gt;</span> <span class="o">.</span><span class="na">flatMap</span><span class="o">(</span><span class="nl">List:</span><span class="o">:</span><span class="n">stream</span><span class="o">)</span> <span class="c1">//Stream&lt;Integer&gt;</span> <span class="o">.</span><span class="na">forEach</span><span class="o">(</span><span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">::</span><span class="n">println</span><span class="o">);</span> <span class="c1">// 1 2 3 4 5 6</span> <span class="o">}</span></code></pre></figure> <p>And in these examples, we already saw another Stream method, <code class="language-plaintext highlighter-rouge">forEach()</code>, which I will describe now.</p> <h3 id="common-stream-methods">Common Stream methods</h3> <h4 id="foreach">forEach</h4> <p>The <code class="language-plaintext highlighter-rouge">forEach</code> method is like the <code class="language-plaintext highlighter-rouge">ifPresent</code> method from Optionals, so you use it when you have side effects. As already shown, you use it to e.g. print all objects in a stream. forEach is one of the few Stream methods that doesn’t return the Stream, so you use it as the last method of a Stream and only once.</p> <p>You should be careful when using forEach, because it causes side effects which we don’t won’t to have. So think twice if you could replace it with another method without side effects.</p> <figure class="highlight"><pre><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kt">void</span> <span class="nf">showForEach</span><span class="o">()</span> <span class="o">{</span> <span class="nc">Stream</span><span class="o">.</span><span class="na">of</span><span class="o">(</span><span class="mi">0</span><span class="o">,</span> <span class="mi">1</span><span class="o">,</span> <span class="mi">2</span><span class="o">,</span> <span class="mi">3</span><span class="o">)</span> <span class="o">.</span><span class="na">forEach</span><span class="o">(</span><span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">::</span><span class="n">println</span><span class="o">);</span> <span class="c1">// 0 1 2 3</span> <span class="o">}</span></code></pre></figure> <h4 id="filter">filter</h4> <p>Filter is a really basic method. It takes a ‘test’ function that takes a value and returns boolean. So it test every object in the Stream. If it passes the test, it will stay in the Stream or otherwise, it will be taken out.</p> <p>This ‘test’ function has the type <code class="language-plaintext highlighter-rouge">Function&lt;T, Boolean&gt;</code>. In the <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html">JavaDoc</a>, you will see that the test function really is of the type <code class="language-plaintext highlighter-rouge">Predicate&lt;T&gt;</code>. But this is just a short form for every function that takes one parameter and returns a boolean.</p> <figure class="highlight"><pre><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kt">void</span> <span class="nf">showFilter</span><span class="o">()</span> <span class="o">{</span> <span class="nc">Stream</span><span class="o">.</span><span class="na">of</span><span class="o">(</span><span class="mi">0</span><span class="o">,</span> <span class="mi">1</span><span class="o">,</span> <span class="mi">2</span><span class="o">,</span> <span class="mi">3</span><span class="o">)</span> <span class="o">.</span><span class="na">filter</span><span class="o">(</span><span class="n">num</span> <span class="o">-&gt;</span> <span class="n">num</span> <span class="o">&lt;</span> <span class="mi">2</span><span class="o">)</span> <span class="o">.</span><span class="na">forEach</span><span class="o">(</span><span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">::</span><span class="n">println</span><span class="o">);</span> <span class="c1">// 0 1</span> <span class="o">}</span></code></pre></figure> <p>Functions that can make your life way easier when creating ‘test’ functions are <code class="language-plaintext highlighter-rouge">Predicate.negate()</code> and <code class="language-plaintext highlighter-rouge">Objects.nonNull()</code>.</p> <p>The first one basically negates the test. Every object which doesn’t pass the original test will pass the negated test and vice versa.</p> <p>The second one can be used as a method reference to get rid of every null object in the Stream. This will help you to prevent <code class="language-plaintext highlighter-rouge">NullPointerExeptions</code> when e.g. mapping functions.</p> <figure class="highlight"><pre><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kt">void</span> <span class="nf">negateFilter</span><span class="o">()</span> <span class="o">{</span> <span class="nc">Predicate</span><span class="o">&lt;</span><span class="nc">Integer</span><span class="o">&gt;</span> <span class="n">small</span> <span class="o">=</span> <span class="n">num</span> <span class="o">-&gt;</span> <span class="n">num</span> <span class="o">&lt;</span> <span class="mi">2</span><span class="o">;</span> <span class="nc">Stream</span><span class="o">.</span><span class="na">of</span><span class="o">(</span><span class="mi">0</span><span class="o">,</span> <span class="mi">1</span><span class="o">,</span> <span class="mi">2</span><span class="o">,</span> <span class="mi">3</span><span class="o">)</span> <span class="o">.</span><span class="na">filter</span><span class="o">(</span><span class="n">small</span><span class="o">.</span><span class="na">negate</span><span class="o">())</span> <span class="c1">// Now every big number passes</span> <span class="o">.</span><span class="na">forEach</span><span class="o">(</span><span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">::</span><span class="n">println</span><span class="o">);</span> <span class="c1">// 2 3</span> <span class="o">}</span> <span class="kd">public</span> <span class="kt">void</span> <span class="nf">filterNull</span><span class="o">()</span> <span class="o">{</span> <span class="nc">Stream</span><span class="o">.</span><span class="na">of</span><span class="o">(</span><span class="mi">0</span><span class="o">,</span> <span class="mi">1</span><span class="o">,</span> <span class="kc">null</span><span class="o">,</span> <span class="mi">3</span><span class="o">)</span> <span class="o">.</span><span class="na">filter</span><span class="o">(</span><span class="nl">Objects:</span><span class="o">:</span><span class="n">nonNull</span><span class="o">)</span> <span class="o">.</span><span class="na">map</span><span class="o">(</span><span class="n">num</span> <span class="o">-&gt;</span> <span class="n">num</span> <span class="o">*</span> <span class="mi">2</span><span class="o">)</span> <span class="c1">// without filter, you would've got a NullPointerExeception</span> <span class="o">.</span><span class="na">forEach</span><span class="o">(</span><span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">::</span><span class="n">println</span><span class="o">);</span> <span class="c1">// 0 2 6</span> <span class="o">}</span></code></pre></figure> <h4 id="collect">collect</h4> <p>As I already said, you want to transform your stream back into another data structure. And that is what you use Collect for. And most of the times, you convert it into a List or a Set.</p> <figure class="highlight"><pre><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kt">void</span> <span class="nf">showCollect</span><span class="o">()</span> <span class="o">{</span> <span class="nc">List</span><span class="o">&lt;</span><span class="nc">Integer</span><span class="o">&gt;</span> <span class="n">filtered</span> <span class="o">=</span> <span class="nc">Stream</span><span class="o">.</span><span class="na">of</span><span class="o">(</span><span class="mi">0</span><span class="o">,</span> <span class="mi">1</span><span class="o">,</span> <span class="mi">2</span><span class="o">,</span> <span class="mi">3</span><span class="o">)</span> <span class="o">.</span><span class="na">filter</span><span class="o">(</span><span class="n">num</span> <span class="o">-&gt;</span> <span class="n">num</span> <span class="o">&lt;</span> <span class="mi">2</span><span class="o">)</span> <span class="o">.</span><span class="na">collect</span><span class="o">(</span><span class="nc">Collectors</span><span class="o">.</span><span class="na">toList</span><span class="o">());</span> <span class="o">}</span></code></pre></figure> <p>But you can use collect for much more. For example, you can join Strings. Therefore, you don’t have the nasty delimiter in the end of the string.</p> <figure class="highlight"><pre><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kt">void</span> <span class="nf">showJoining</span><span class="o">()</span> <span class="o">{</span> <span class="nc">String</span> <span class="n">sentence</span> <span class="o">=</span> <span class="nc">Stream</span><span class="o">.</span><span class="na">of</span><span class="o">(</span><span class="s">"Who"</span><span class="o">,</span> <span class="s">"are"</span><span class="o">,</span> <span class="s">"you?"</span><span class="o">)</span> <span class="o">.</span><span class="na">collect</span><span class="o">(</span><span class="nc">Collectors</span><span class="o">.</span><span class="na">joining</span><span class="o">(</span><span class="s">" "</span><span class="o">));</span> <span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">sentence</span><span class="o">);</span> <span class="c1">// Who are you?</span> <span class="o">}</span></code></pre></figure> <h3 id="shortcuts">Shortcuts</h3> <p>These are methods which you could mostly emulate by using map, filter and collect, but these shortcut method are meant to be used because they declutter your code.</p> <h4 id="reduce">reduce</h4> <p>Reduce is a very cool function.</p> <p>It takes a start parameter of type T and a Function of type <code class="language-plaintext highlighter-rouge">BiFunction&lt;T, T, T&gt;</code>. If you have a BiFunction where all types are the same, <code class="language-plaintext highlighter-rouge">BinaryOperator&lt;T&gt;</code> is a shortcut for that.</p> <p>It basically stores all objects in the stream to one object. You can concat all Strings into one String, sum all numbers and so on. There, your start parameters would be the empty String or zero. This function helps a lot to make your code more readable if you know how to use it.</p> <figure class="highlight"><pre><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kt">void</span> <span class="nf">showReduceSum</span><span class="o">()</span> <span class="o">{</span> <span class="nc">Integer</span> <span class="n">sum</span> <span class="o">=</span> <span class="nc">Stream</span><span class="o">.</span><span class="na">of</span><span class="o">(</span><span class="mi">1</span><span class="o">,</span> <span class="mi">2</span><span class="o">,</span> <span class="mi">3</span><span class="o">)</span> <span class="o">.</span><span class="na">reduce</span><span class="o">(</span><span class="mi">0</span><span class="o">,</span> <span class="nl">Integer:</span><span class="o">:</span><span class="n">sum</span><span class="o">);</span> <span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">sum</span><span class="o">);</span> <span class="c1">// 6</span> <span class="o">}</span></code></pre></figure> <p>Now I will give a little bit more information how reduce works. Here, it sums</p> <p>the first number with</p> <p>the sum of the second and</p> <p>    the sum of the third and start parameter.</p> <p>As you can see, this produces a long chain of functions. In the end, we have sum(1, sum(2, sum(3, 0))). And this will be computed from right to left, or from the inside out. This is also the reason we need a start parameter, because otherwise the chain would’nt have a point where it could end.</p> <h4 id="sorted">sorted</h4> <p>You can also use Streams to sort your data structure.</p> <p>The class type of the objects in the Stream doesn’t even have to implement <code class="language-plaintext highlighter-rouge">Comperable&lt;T&gt;</code>, because you can write your own <code class="language-plaintext highlighter-rouge">Comperator&lt;T&gt;</code>. This is basically a <code class="language-plaintext highlighter-rouge">BiFunction&lt;T, T, int&gt;</code>, but Comperator is a shortcut for all BiFunctions that take 2 arguments of the same type and return an int.</p> <p>And this int, like in the <code class="language-plaintext highlighter-rouge">compareTo()</code> function, shows us if the first object is “smaller” than the first one (int &lt; 0), is as big as the second (int == 0), or is bigger than the second one (int &gt; 0). The sorted function of the Stream will interpret these ints and will sort the elements with the help of them.</p> <figure class="highlight"><pre><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kt">void</span> <span class="nf">showSort</span><span class="o">()</span> <span class="o">{</span> <span class="nc">Stream</span><span class="o">.</span><span class="na">of</span><span class="o">(</span><span class="mi">3</span><span class="o">,</span> <span class="mi">2</span><span class="o">,</span> <span class="mi">4</span><span class="o">,</span> <span class="mi">0</span><span class="o">)</span> <span class="o">.</span><span class="na">sorted</span><span class="o">((</span><span class="n">c1</span><span class="o">,</span> <span class="n">c2</span><span class="o">)</span> <span class="o">-&gt;</span> <span class="n">c1</span> <span class="o">-</span> <span class="n">c2</span><span class="o">)</span> <span class="o">.</span><span class="na">forEach</span><span class="o">(</span><span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">::</span><span class="n">println</span><span class="o">);</span> <span class="c1">// 0 2 3 4</span> <span class="o">}</span></code></pre></figure> <h4 id="other-kinds-of-streams">Other Kinds of Streams</h4> <p>There are also special types of Streams which only contains numbers. With these new Streams you also have a new set of methods.</p> <p>Here, I will introduce IntStream and Sum, but there are also LongStream, DoubleStream,… . You can read more about them in the <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html">JavaDoc</a>.</p> <p>To convert a normal Stream into an IntStream, you have to use <code class="language-plaintext highlighter-rouge">mapToInt</code>. It does exactly the same as the normal map, but you get a IntStream back. Of course, you have to give the mapToInt function another function which will return an int.</p> <p>In the example, I will show you how to sum numbers without reduce, but with an IntStream.</p> <figure class="highlight"><pre><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kt">void</span> <span class="nf">sumWithIntStream</span><span class="o">()</span> <span class="o">{</span> <span class="nc">Integer</span> <span class="n">sum</span> <span class="o">=</span> <span class="nc">Stream</span><span class="o">.</span><span class="na">of</span><span class="o">(</span><span class="mi">0</span><span class="o">,</span> <span class="mi">1</span><span class="o">,</span> <span class="mi">2</span><span class="o">,</span> <span class="mi">3</span><span class="o">)</span> <span class="o">.</span><span class="na">mapToInt</span><span class="o">(</span><span class="n">num</span> <span class="o">-&gt;</span> <span class="n">num</span><span class="o">)</span> <span class="o">.</span><span class="na">sum</span><span class="o">();</span> <span class="o">}</span></code></pre></figure> <h3 id="use-streams-for-tests">Use Streams for Tests</h3> <p>Tests can also be used to test your methods. I will use the method <code class="language-plaintext highlighter-rouge">anyMatch</code> here, but <code class="language-plaintext highlighter-rouge">count</code>, <code class="language-plaintext highlighter-rouge">max</code> and so on can help you too.</p> <p>If something goes wrong in your program, use <code class="language-plaintext highlighter-rouge">peek</code> to log data. It’s like forEach, but also returns the stream. As always, look into the <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html">JavaDoc</a> to find other cool methods.</p> <p><code class="language-plaintext highlighter-rouge">anyMatch</code> is a little bit like filter, but it tells you if anything passes the filter. You can use this in <code class="language-plaintext highlighter-rouge">assertTrue()</code> tests, where you just want to look if at least one object has a specific property.</p> <p>In the next example, I will test if a specific name was stored in the DB.</p> <figure class="highlight"><pre><code class="language-java" data-lang="java"><span class="nd">@Test</span> <span class="kd">public</span> <span class="kt">void</span> <span class="nf">testIfNameIsStored</span><span class="o">()</span> <span class="o">{</span> <span class="nc">String</span> <span class="n">testName</span> <span class="o">=</span> <span class="s">"Albert Einstein"</span><span class="o">;</span> <span class="nc">Datebase</span> <span class="n">names</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">Datebase</span><span class="o">();</span> <span class="n">names</span><span class="o">.</span><span class="na">drop</span><span class="o">();</span> <span class="n">db</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="n">testName</span><span class="o">);</span> <span class="n">assertTrue</span><span class="o">(</span><span class="n">db</span><span class="o">.</span><span class="na">getData</span><span class="o">()</span> <span class="o">.</span><span class="na">stream</span><span class="o">()</span> <span class="o">.</span><span class="na">anyMatch</span><span class="o">(</span><span class="n">name</span> <span class="o">-&gt;</span> <span class="n">name</span><span class="o">.</span><span class="na">equals</span><span class="o">(</span><span class="n">testName</span><span class="o">)));</span> <span class="o">}</span></code></pre></figure> <h3 id="shortcuts-of-shortcuts">Shortcuts of Shortcuts</h3> <p>And after I showed you some shortcut methods, I want to tell you that there are many, many more. There are even shortcuts of shortcuts! One Example would be <code class="language-plaintext highlighter-rouge">max</code>, which combines <code class="language-plaintext highlighter-rouge">sorted</code> and <code class="language-plaintext highlighter-rouge">findFirst</code>.</p> <p>If you are interested in other helpful methods, look into the <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html">JavaDoc</a>. I’m sure you are prepared to understand it and find the methods that you need. Always remember: If your code looks ugly, there’s a better method to use ;).</p> <h3 id="a-bigger-example">A Bigger Example</h3> <p>In this example, we want to send a message to every user whose birthday’s today.</p> <h4 id="the-user-class">The User Class</h4> <p>A user is defined by their username and birthday. The birthdays will be in the format “day.month.year”, but we won’t do much checking for this in today’s example.</p> <figure class="highlight"><pre><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">User</span> <span class="o">{</span> <span class="kd">private</span> <span class="nc">String</span> <span class="n">username</span><span class="o">;</span> <span class="kd">private</span> <span class="nc">String</span> <span class="n">birthday</span><span class="o">;</span> <span class="kd">public</span> <span class="nf">User</span><span class="o">(</span><span class="nc">String</span> <span class="n">username</span><span class="o">,</span> <span class="nc">String</span> <span class="n">birthday</span><span class="o">)</span> <span class="o">{</span> <span class="k">this</span><span class="o">.</span><span class="na">username</span> <span class="o">=</span> <span class="n">username</span><span class="o">;</span> <span class="k">this</span><span class="o">.</span><span class="na">birthday</span> <span class="o">=</span> <span class="n">birthday</span><span class="o">;</span> <span class="o">}</span> <span class="kd">public</span> <span class="nc">String</span> <span class="nf">getUsername</span><span class="o">()</span> <span class="o">{</span> <span class="k">return</span> <span class="n">username</span><span class="o">;</span> <span class="o">}</span> <span class="kd">public</span> <span class="nc">String</span> <span class="nf">getBirthday</span><span class="o">()</span> <span class="o">{</span> <span class="k">return</span> <span class="n">birthday</span><span class="o">;</span> <span class="o">}</span> <span class="o">}</span></code></pre></figure> <p>To store all users, we will use a List here. In a real program, you might want to switch to a DB.</p> <figure class="highlight"><pre><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">MainClass</span> <span class="o">{</span> <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">()</span> <span class="o">{</span> <span class="nc">List</span><span class="o">&lt;</span><span class="nc">User</span><span class="o">&gt;</span> <span class="n">users</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">LinkedList</span><span class="o">&lt;&gt;();</span> <span class="nc">User</span> <span class="n">birthdayChild</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">User</span><span class="o">(</span><span class="s">"peter"</span><span class="o">,</span> <span class="s">"20.02.1990"</span><span class="o">);</span> <span class="nc">User</span> <span class="n">otherUser</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">User</span><span class="o">(</span><span class="s">"kid"</span><span class="o">,</span> <span class="s">"23.02.2008"</span><span class="o">);</span> <span class="nc">User</span> <span class="n">birthdayChild2</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">User</span><span class="o">(</span><span class="s">"bruce"</span><span class="o">,</span> <span class="s">"20.02.1980"</span><span class="o">);</span> <span class="n">users</span><span class="o">.</span><span class="na">addAll</span><span class="o">(</span><span class="nc">Arrays</span><span class="o">.</span><span class="na">asList</span><span class="o">(</span><span class="n">birthdayChild</span><span class="o">,</span> <span class="n">otherUser</span><span class="o">,</span> <span class="n">birthdayChild2</span><span class="o">));</span> <span class="n">greetAllBirthdayChildren</span><span class="o">(</span><span class="n">users</span><span class="o">);</span> <span class="o">}</span> <span class="kd">private</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">greetAllBirthdayChildren</span><span class="o">(</span><span class="nc">List</span><span class="o">&lt;</span><span class="nc">User</span><span class="o">&gt;</span> <span class="n">users</span><span class="o">)</span> <span class="o">{</span> <span class="c1">// Next Section</span> <span class="o">}</span> <span class="o">}</span></code></pre></figure> <h4 id="the-greeting">The Greeting</h4> <p>Now, we want to greet the birthday children.</p> <p>So first off, we have to filter out all Users whose birthday is today. After this, we have to message them. So let’s do this.</p> <p>I won’t implement <code class="language-plaintext highlighter-rouge">sendMessage(String message, User receiver)</code> here, but it just sends a message to a given user.</p> <figure class="highlight"><pre><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">greetAllBirthdayChildren</span><span class="o">(</span><span class="nc">List</span><span class="o">&lt;</span><span class="nc">User</span><span class="o">&gt;</span> <span class="n">users</span><span class="o">)</span> <span class="o">{</span> <span class="nc">String</span> <span class="n">today</span> <span class="o">=</span> <span class="s">"20.02"</span><span class="o">;</span> <span class="c1">//Just to make the example easier. In production, you would use LocalDateTime or so.</span> <span class="n">users</span><span class="o">.</span><span class="na">stream</span><span class="o">()</span> <span class="o">.</span><span class="na">filter</span><span class="o">(</span><span class="n">user</span> <span class="o">-&gt;</span> <span class="n">user</span><span class="o">.</span><span class="na">getBirthday</span><span class="o">().</span><span class="na">startsWith</span><span class="o">(</span><span class="n">today</span><span class="o">))</span> <span class="o">.</span><span class="na">forEach</span><span class="o">(</span><span class="n">user</span> <span class="o">-&gt;</span> <span class="n">sendMessage</span><span class="o">(</span><span class="s">"Happy birthday, "</span><span class="o">.</span><span class="na">concat</span><span class="o">(</span><span class="n">user</span><span class="o">.</span><span class="na">getUsername</span><span class="o">()).</span><span class="na">concat</span><span class="o">(</span><span class="s">"!"</span><span class="o">),</span> <span class="n">user</span><span class="o">));</span> <span class="o">}</span> <span class="kd">private</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">sendMessage</span><span class="o">(</span><span class="nc">String</span> <span class="n">message</span><span class="o">,</span> <span class="nc">User</span> <span class="n">receiver</span><span class="o">)</span> <span class="o">{</span> <span class="c1">//...</span> <span class="o">}</span></code></pre></figure> <p>And now we can send greetings to the users. How nice and easy was that?!</p> <h3 id="parallelism">Parallelism</h3> <p>Streams can also be executed parallel. By default, every Stream isn’t parallel, but you can use <code class="language-plaintext highlighter-rouge">.parallelStream()</code> with Streams to make them parallel.</p> <p>Although it can be cool to use this to make your program faster, you should be careful with it. As shown on <a href="https://docs.oracle.com/javase/tutorial/collections/streams/parallelism.html">this Site</a>, things like sorting can be messed up by parallelism.</p> <p>So be prepared to run into nasty bugs with parallel Streams, although it can make your program significantly faster.</p> <h2 id="conclusion">Conclusion</h2> <p>That’s it for today!</p> <p>We have learned a lot about Streams in Java. We learned how to convert a data structure into a Stream, how to work with a Stream and how to convert your Stream back into a data structure.</p> <p>I have introduced the most common methods and when you should use them.</p> <p>In the end, we tested our knowledge with a bigger example where we greeted all birthday children.</p> <p>In the next part of this series, we will have a big example where we are going to use Streams. But I won’t tell you the example yet, so be surprised.</p> <p>Are there any Stream methods that you miss in the post? Please let me know in the comments. I’d love to hear your feedback too!</p> <p>Thanks for reading and have a nice day,</p> <p>Niklas</p> Sat, 18 Feb 2017 12:00:00 +0000 flyingbytes.github.io/programming/java8/functional/part3/2017/02/18/Java8-Part3.html flyingbytes.github.io/programming/java8/functional/part3/2017/02/18/Java8-Part3.html programming java8 functional part3 An Introduction to Functional Programming in Java 8: Part 2 - Optionals <p>Hello everybody,</p> <p>After we’ve made our first big steps into functional programming in the <a href="https://flyingbytes.github.io/programming/java8/functional/part1/2017/01/23/Java8-Part1.html">last post</a>, we will talk about Optionals in today’s part.</p> <h2 id="why-do-we-need-optionals">Why do we need Optionals?</h2> <p>Hand on heart, you also think that null is annoying, don’t you? For every argument which can be null, you have to check whether it is null or not.</p> <figure class="highlight"><pre><code class="language-java" data-lang="java"><span class="k">if</span><span class="o">(</span><span class="n">argument</span> <span class="o">==</span> <span class="kc">null</span><span class="o">)</span> <span class="o">{</span> <span class="k">throw</span> <span class="k">new</span> <span class="nf">NullPointerException</span><span class="o">();</span> <span class="o">}</span></code></pre></figure> <p>These lines suck! This is a boilerplate that bloats up your code and can be easily forgotten. So how can we fix that?</p> <h2 id="introducing-optionals">Introducing Optionals</h2> <p>In Java 8, <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html">java.util.Optional&lt;T&gt;</a> was introduced to handle objects which might not exist better. It is a container object that can hold another object. The Generic <em>T</em> is the type of the object you want to contain.</p> <figure class="highlight"><pre><code class="language-java" data-lang="java"><span class="nc">Integer</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">5</span><span class="o">;</span> <span class="nc">Optional</span><span class="o">&lt;</span><span class="nc">Integer</span><span class="o">&gt;</span> <span class="n">optinalI</span> <span class="o">=</span> <span class="nc">Optional</span><span class="o">.</span><span class="na">of</span><span class="o">(</span><span class="n">i</span><span class="o">);</span></code></pre></figure> <p>The Optional class doesn’t have any public constructor. To create an optional, you have to use <code class="language-plaintext highlighter-rouge">Optional.of(object)</code> or <code class="language-plaintext highlighter-rouge">Optional.ofNullable(object)</code>. You use the first one if the object is never, ever null. The second one is used for nullable objects.</p> <h3 id="how-do-optionals-work">How do optionals work?</h3> <p>Options have two states. They either hold an object or they hold null. If they hold an object, optionals are called <em>present</em>, if they hold null, they are called <em>empty</em>. If they are not empty, you can get the object in the optional by using <code class="language-plaintext highlighter-rouge">Optional.get()</code>. But be careful, because a <em>get()</em> on an empty optional will cause a <code class="language-plaintext highlighter-rouge">NoSuchElementException</code>. You can check if a optional is present by calling the method <code class="language-plaintext highlighter-rouge">Optional.isPresent()</code></p> <h4 id="example-playing-with-optionals">Example: Playing with Optionals</h4> <figure class="highlight"><pre><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kt">void</span> <span class="nf">playingWithOptionals</span><span class="o">()</span> <span class="o">{</span> <span class="nc">String</span> <span class="n">s</span> <span class="o">=</span> <span class="s">"Hello World!"</span><span class="o">;</span> <span class="nc">String</span> <span class="n">nullString</span> <span class="o">=</span> <span class="kc">null</span><span class="o">;</span> <span class="nc">Optional</span><span class="o">&lt;</span><span class="nc">String</span><span class="o">&gt;</span> <span class="n">optionalS1</span> <span class="o">=</span> <span class="nc">Optional</span><span class="o">.</span><span class="na">of</span><span class="o">(</span><span class="n">s</span><span class="o">);</span> <span class="c1">// Will work</span> <span class="nc">Optional</span><span class="o">&lt;</span><span class="nc">String</span><span class="o">&gt;</span> <span class="n">optionalS2</span> <span class="o">=</span> <span class="nc">Optional</span><span class="o">.</span><span class="na">ofNullable</span><span class="o">(</span><span class="n">s</span><span class="o">);</span> <span class="c1">// Will work too</span> <span class="nc">Optional</span><span class="o">&lt;</span><span class="nc">String</span><span class="o">&gt;</span> <span class="n">optionalNull1</span> <span class="o">=</span> <span class="nc">Optional</span><span class="o">.</span><span class="na">of</span><span class="o">(</span><span class="n">nullString</span><span class="o">);</span> <span class="c1">// -&gt; NullPointerException</span> <span class="nc">Optional</span><span class="o">&lt;</span><span class="nc">String</span><span class="o">&gt;</span> <span class="n">optionalNull2</span> <span class="o">=</span> <span class="nc">Optional</span><span class="o">.</span><span class="na">ofNullable</span><span class="o">(</span><span class="n">nullString</span><span class="o">);</span> <span class="c1">// Will work</span> <span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">optionalS1</span><span class="o">.</span><span class="na">get</span><span class="o">());</span> <span class="c1">// prints "Hello World!"</span> <span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">optionalNull2</span><span class="o">.</span><span class="na">get</span><span class="o">());</span> <span class="c1">// -&gt; NoSuchElementException</span> <span class="k">if</span><span class="o">(!</span><span class="n">optionalNull2</span><span class="o">.</span><span class="na">isPresent</span><span class="o">())</span> <span class="o">{</span> <span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">"Is empty"</span><span class="o">);</span> <span class="c1">// Will be printed</span> <span class="o">}</span> <span class="o">}</span></code></pre></figure> <h2 id="common-problems-when-using-optionals">Common problems when using Optionals</h2> <h3 id="1-working-with-optional-and-null">1. Working with Optional <strong>and</strong> null</h3> <figure class="highlight"><pre><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kt">void</span> <span class="nf">workWithFirstStringInDB</span><span class="o">()</span> <span class="o">{</span> <span class="nc">DBConnection</span> <span class="n">dB</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">DBConnection</span><span class="o">();</span> <span class="nc">Optional</span><span class="o">&lt;</span><span class="nc">String</span><span class="o">&gt;</span> <span class="n">first</span> <span class="o">=</span> <span class="n">dB</span><span class="o">.</span><span class="na">getFirstString</span><span class="o">();</span> <span class="k">if</span><span class="o">(</span><span class="n">first</span> <span class="o">!=</span> <span class="kc">null</span><span class="o">)</span> <span class="o">{</span> <span class="nc">String</span> <span class="n">value</span> <span class="o">=</span> <span class="n">first</span><span class="o">.</span><span class="na">get</span><span class="o">();</span> <span class="c1">//... </span> <span class="o">}</span> <span class="o">}</span></code></pre></figure> <p>This is just the wrong use of an Optional! If you get an Optional (In the example you get one from the DB), you don’t have to look whether the object is null or not! If there’s no string in the DB, it will return <code class="language-plaintext highlighter-rouge">Optional.empty()</code>, not <code class="language-plaintext highlighter-rouge">null</code>! If you got an empty Optional from the DB, there would also be a <code class="language-plaintext highlighter-rouge">NoSuchElementException</code> in this example.</p> <h3 id="2-using-ispresent-and-get">2. Using isPresent() and get()</h3> <h4 id="21-doing-something-when-the-value-is-present">2.1. Doing something when the value is present</h4> <figure class="highlight"><pre><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kt">void</span> <span class="nf">workWithFirstStringInDB</span><span class="o">()</span> <span class="o">{</span> <span class="nc">DBConnection</span> <span class="n">dB</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">DBConnection</span><span class="o">();</span> <span class="nc">Optional</span><span class="o">&lt;</span><span class="nc">String</span><span class="o">&gt;</span> <span class="n">first</span> <span class="o">=</span> <span class="n">dB</span><span class="o">.</span><span class="na">getFirstString</span><span class="o">();</span> <span class="k">if</span><span class="o">(</span><span class="n">first</span><span class="o">.</span><span class="na">isPresent</span><span class="o">())</span> <span class="o">{</span> <span class="nc">String</span> <span class="n">value</span> <span class="o">=</span> <span class="n">first</span><span class="o">.</span><span class="na">get</span><span class="o">();</span> <span class="c1">//... </span> <span class="o">}</span> <span class="o">}</span></code></pre></figure> <p>As I already said, you should always be 100% sure if an Optional is present before you use <code class="language-plaintext highlighter-rouge">Optional.get()</code>. You wouldn’t get a <code class="language-plaintext highlighter-rouge">NoSuchElementException</code> anymore in the updated function. But you shouldn’t check a optional with the <code class="language-plaintext highlighter-rouge">isPresent() + get()</code> combo! Because if you do it like that, you could have used <em>null</em> in the first place. You would replace <code class="language-plaintext highlighter-rouge">first.isPresent()</code> with <code class="language-plaintext highlighter-rouge">first != null</code> and you have the same result. But how can we replace this annoying if-block with the help of Optionals?</p> <figure class="highlight"><pre><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kt">void</span> <span class="nf">workWithFirstStringInDB</span><span class="o">()</span> <span class="o">{</span> <span class="nc">DBConnection</span> <span class="n">dB</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">DBConnection</span><span class="o">();</span> <span class="nc">Optional</span><span class="o">&lt;</span><span class="nc">String</span><span class="o">&gt;</span> <span class="n">first</span> <span class="o">=</span> <span class="n">dB</span><span class="o">.</span><span class="na">getFirstString</span><span class="o">();</span> <span class="n">first</span><span class="o">.</span><span class="na">ifPresent</span><span class="o">(</span><span class="n">value</span> <span class="o">-&gt;</span> <span class="cm">/*...*/</span><span class="o">);</span> <span class="o">}</span></code></pre></figure> <p>The <code class="language-plaintext highlighter-rouge">Optional.ifPresent()</code> method is our new best friend to replace the if. It takes a Function, so a Lambda or method reference, and applies it only when the value is present. If you don’t remember how to use method references or Lambdas, you should read the <a href="https://flyingbytes.github.io/programming/java8/functional/part1/2017/01/23/Java8-Part1.html">last part</a> of this series again.</p> <p>You use ifPresent() when you want to do something that produces a side effect. Storing something in the DB and IO are two common examples for side effects. If you don’t need side effects, you shouldn’t use ifPresent(), but map(), which is part of the next section.</p> <h4 id="22-returning-a-modified-version-of-the-value">2.2. Returning a Modified Version of the Value</h4> <figure class="highlight"><pre><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="nc">Integer</span> <span class="nf">doubleValueOrZero</span><span class="o">(</span><span class="nc">Optional</span><span class="o">&lt;</span><span class="nc">Integer</span><span class="o">&gt;</span> <span class="n">value</span><span class="o">)</span> <span class="o">{</span> <span class="k">if</span><span class="o">(</span><span class="n">value</span><span class="o">.</span><span class="na">isPresent</span><span class="o">())</span> <span class="o">{</span> <span class="k">return</span> <span class="n">value</span><span class="o">.</span><span class="na">get</span><span class="o">()</span> <span class="o">*</span> <span class="mi">2</span><span class="o">;</span> <span class="o">}</span> <span class="k">return</span> <span class="mi">0</span><span class="o">;</span> <span class="o">}</span></code></pre></figure> <p>In this method, we want to double the value of an optional, if it is present. Otherwise, we return zero. The given example works, but it isn’t the functional way of solving this problem. To make this a lot nicer, we have two function that are coming to help us. The first one’s <code class="language-plaintext highlighter-rouge">Optional.map(Function&lt;T, R&gt; mapper)</code> and the second one’s <code class="language-plaintext highlighter-rouge">Optional.orElse(T other)</code>. <code class="language-plaintext highlighter-rouge">map</code> takes a function, applies it on the value and returns the result of the function, wrapped in an Optional again. If the Optional is empty, it will return an empty Optional again. <code class="language-plaintext highlighter-rouge">orElse</code> returns the value of the Optional it is called on. If there is no value, it returns the value you gave <code class="language-plaintext highlighter-rouge">orElse(object)</code> as a parameter. With that in mind, we can make this function a one liner.</p> <figure class="highlight"><pre><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="nc">Integer</span> <span class="nf">doubleValueOrZero</span><span class="o">(</span><span class="nc">Optional</span><span class="o">&lt;</span><span class="nc">Integer</span><span class="o">&gt;</span> <span class="n">value</span><span class="o">)</span> <span class="o">{</span> <span class="k">return</span> <span class="n">value</span><span class="o">.</span><span class="na">map</span><span class="o">(</span><span class="n">i</span> <span class="o">-&gt;</span> <span class="n">i</span> <span class="o">*</span> <span class="mi">2</span><span class="o">).</span><span class="na">orElse</span><span class="o">(</span><span class="mi">0</span><span class="o">);</span> <span class="o">}</span></code></pre></figure> <h2 id="using-flatmap">Using flatMap()</h2> <p>There is another really cool method that you can use with Optionals. It’s called <code class="language-plaintext highlighter-rouge">flatMap()</code>.</p> <p>When you use map on a method that returns an Optional, you basically get an Optional&lt;Optional&lt;T&gt;&gt;. But you don’t want two containers abound your object! But you also don’t want to rewrite the method nor do you want to call get() or orElse() two times to get the value.</p> <p>This is the reason there is flatMap. It flattens the Optional&lt;Optional&lt;T&gt;&gt; to Optional&lt;T&gt;. In our example, we want to divide 2 Integers. But if we divide by zero, we return <code class="language-plaintext highlighter-rouge">Optional.empty()</code>. So if we use map and divide, we have a object of type Optional&lt;Optional&lt;Double&gt;&gt;. That’s the reason we use flatMap here.</p> <figure class="highlight"><pre><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kt">void</span> <span class="nf">showFlatMap</span><span class="o">()</span> <span class="o">{</span> <span class="nc">Optional</span><span class="o">&lt;</span><span class="nc">Double</span><span class="o">&gt;</span> <span class="n">two</span> <span class="o">=</span> <span class="nc">Optional</span><span class="o">.</span><span class="na">of</span><span class="o">(</span><span class="mf">2.0</span><span class="o">);</span> <span class="nc">Optional</span><span class="o">&lt;</span><span class="nc">Double</span><span class="o">&gt;</span> <span class="n">zero</span> <span class="o">=</span> <span class="nc">Optional</span><span class="o">.</span><span class="na">of</span><span class="o">(</span><span class="mf">0.0</span><span class="o">);</span> <span class="n">two</span><span class="o">.</span><span class="na">flatMap</span><span class="o">(</span><span class="n">num</span> <span class="o">-&gt;</span> <span class="n">divide</span><span class="o">(</span><span class="mf">1.0</span><span class="o">,</span> <span class="n">num</span><span class="o">)).</span><span class="na">orElse</span><span class="o">(</span><span class="mf">0.0</span><span class="o">);</span> <span class="c1">// 0.5</span> <span class="n">zero</span><span class="o">.</span><span class="na">flatMap</span><span class="o">(</span><span class="n">num</span> <span class="o">-&gt;</span> <span class="n">divide</span><span class="o">(</span><span class="mf">1.0</span><span class="o">,</span> <span class="n">num</span><span class="o">)).</span><span class="na">orElse</span><span class="o">(</span><span class="mf">0.0</span><span class="o">);</span> <span class="c1">// 0.0</span> <span class="o">}</span> <span class="kd">public</span> <span class="nc">Optional</span><span class="o">&lt;</span><span class="nc">Double</span><span class="o">&gt;</span> <span class="nf">divide</span><span class="o">(</span><span class="nc">Double</span> <span class="n">first</span><span class="o">,</span> <span class="nc">Double</span> <span class="n">second</span><span class="o">)</span> <span class="o">{</span> <span class="k">if</span><span class="o">(</span><span class="n">second</span> <span class="o">==</span> <span class="mf">0.0</span><span class="o">)</span> <span class="o">{</span> <span class="k">return</span> <span class="nc">Optional</span><span class="o">.</span><span class="na">empty</span><span class="o">();</span> <span class="o">}</span> <span class="k">return</span> <span class="nc">Optional</span><span class="o">.</span><span class="na">of</span><span class="o">(</span><span class="n">first</span> <span class="o">/</span> <span class="n">second</span><span class="o">);</span> <span class="o">}</span></code></pre></figure> <h2 id="when-should-you-use-nullable-objects-and-when-optionals">When Should you use Nullable Objects and when Optionals?</h2> <p>You can find a lot of books, <a href="https://www.youtube.com/watch?v=Ej0sss6cq14">talks</a> and discussions about the question: Should you use null or Optional in some particular case. And both have their right to be used. In the linked talk, you will find a nice rule which you can apply in most of the cases. Use Optionals when <em>“there is a clear need to represent ‘no result’ or where null is likely to cause errors.”</em>.</p> <p>So you shouldn’t use Optionals like this:</p> <figure class="highlight"><pre><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="nc">String</span> <span class="nf">defaultIfOptional</span><span class="o">(</span><span class="nc">String</span> <span class="n">string</span><span class="o">)</span> <span class="o">{</span> <span class="k">return</span> <span class="nc">Optional</span><span class="o">.</span><span class="na">ofNullable</span><span class="o">(</span><span class="n">string</span><span class="o">).</span><span class="na">orElse</span><span class="o">(</span><span class="s">"default"</span><span class="o">);</span> <span class="o">}</span></code></pre></figure> <p>Because a null check is much easier to read.</p> <figure class="highlight"><pre><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="nc">String</span> <span class="nf">defaultIfOptional</span><span class="o">(</span><span class="nc">String</span> <span class="n">string</span><span class="o">)</span> <span class="o">{</span> <span class="k">return</span> <span class="o">(</span><span class="n">string</span> <span class="o">!=</span> <span class="kc">null</span><span class="o">)</span> <span class="o">?</span> <span class="n">string</span> <span class="o">:</span> <span class="s">"default"</span><span class="o">;</span> <span class="o">}</span></code></pre></figure> <p>You should use Optionals just as a return value from a function. It’s not a good idea to create new ones to make a cool method chain like in the example above. Most of the times, null is enough.</p> <h2 id="conclusion">Conclusion</h2> <p>That’s it for today! We have played with the Optional class. It’s a container class for other classes which is either present or not present(<em>empty</em>). We have removed some common code smell that comes with Optionals and used functions as objects again. We also discussed when you should use null and when Optionals.</p> <p>In the next part, we will use <em>Streams</em> as a new way to handle a Collection of Objects.</p> <p>Thanks for reading and have a nice day,</p> <p>Niklas</p> Sat, 04 Feb 2017 12:00:00 +0000 flyingbytes.github.io/programming/java8/functional/part2/2017/02/04/Java8-Part2.html flyingbytes.github.io/programming/java8/functional/part2/2017/02/04/Java8-Part2.html programming java8 functional part2