Automatically Improving Code in IntelliJ IDEA (Java 13)

KonfHub
2 min readOct 17, 2019
Java Stream processing is fun!

In this blog post, I show a simple example of how you can simplify your code (on stream processing) by automatically improving the code in IntelliJ IDEA.

Let’s start with a simple string:

var pearlOfWisdom = "follow your heart but take your head with you";

You can split this sentence like this to get an array of words:

var words = pearlOfWisdom.split(" ");

Now, let’s print the words:

Arrays.stream(words)
.forEach(System.out::println);

This prints:

follow
your
heart
but
take
your
head
with
you

Note that there are some duplicates (“your”). Let’s remove it by calling distinct():

Arrays.stream(words)
.distinct()
.forEach(System.out::println);

Now, let’s sort by length of the words. If you use this code, it is verbose:

.sorted((str1, str2) -> str1.length() - str2.length())

Fortunately, IntelliJ IDEA automatically suggests a refactoring to the following:

.sorted(comparingInt(String::length))

Sweet. Now, let’s compare the words first by length of the words, and then the words of same length by the “natural ordering of the words”:

.sorted(comparingInt(String::length).thenComparing((str1, str2) -> str1.compareTo(str2)))

This is lengthy and it sucks. Fortunately, IntelliJ to the rescue again and pressing Alt + Enter makes this code simpler like this:

.sorted(comparingInt(String::length).thenComparing(naturalOrder()))

Now, let’s reverse the words:

.sorted(comparingInt(String::length).thenComparing(naturalOrder()).reversed())

Ah! That’s too long — let’s extract it to a method. You can do it automatically by selecting the Alt + Command + M and give a suitable name:

private static Comparator<String> compareByLenNaturalOrderReversed() {
return comparingInt(String::length)
.thenComparing(naturalOrder())
.reversed();
}

With this the code looks like this:

package com.company;

import java.util.Arrays;
import java.util.Comparator;

import static java.util.Comparator.*;
import static java.util.Comparator.comparingInt;

class ProcessWords {
public static void main(String[] args) {
var pearlOfWisdom = "follow your heart but take your head with you";
var words = pearlOfWisdom.split(" ");
Arrays.stream(words)
.distinct()
.sorted(compareByLenNaturalOrderReversed())
.forEach(System.out::println);
}

private static Comparator<String> compareByLenNaturalOrderReversed() {
return comparingInt(String::length).thenComparing(naturalOrder()).reversed();
}
}

This program prints:

follow
heart
your
with
take
head
you
but

Now its time to try it on your own. You may want to watch the supporting YouTube video showing this coding in action here.

https://youtu.be/C_vLBLWwfz4

See you soon, until then bye!

--

--

KonfHub

KonfHub is the one-stop platform to create and host tech events. Create the event in under 30 seconds, gamify & amplify for audience engagement!