Archive for category programming

Java 8: Converting Optional Collection to the Streams API

Although Java 9 has already been released, this post is about converting an optional collection to the Streams API introduced in Java 8.

Suppose some person could have zero, one or more cars and it is represented by the Person class below (some code omitted).

Now we create a list of people and we want to get Mark’s cars.

How can we do that using the Streams API, since the getCars() method return an Optional?

One possibility is to filter people’s list by Mark’s name, filter the Optional if it is present or not and map its wrapped value (our cars list):

At this moment we reached the reason of this blog post. And how can we get all people’s cars? The idea here is to use the flatMap() operation unwrapping the Optional to the collection’s stream when it is present or getting an empty stream when it isn’t present:

We can do better and replace the above solution to be more functional using method references:

If you use IntelliJ IDEA as your favorite IDE, it has an inspection that helps replacing Optional.isPresent() with a functional expression:

P.S. In Java 9, the stream() method was added to the Optional API, so we can rewrite the above stream pipeline into the following one:

In case you are interested, this post on the IntelliJ IDEA blog has some good tips when working with Java 8.

Tags: , , , , , , , , , ,

About the Kotlin programming language

Kotlin is a statically typed language which is fully interoperable with Java.

Recently my friend Andre showed me Kotlin‘s nice syntax and I considered giving it a try.

In the meantime, my friend Leonnardo sent me this nice link which helps migrating from Java to Kotlin easily.

Let’s compare some syntax from Java and Kotlin and see the differences. Suppose we have some employees and we want to group them by their departments.

In Java we create an Employee class, build some employees and use the Streams API to group them by their departments:

In Kotlin we create a data class Employee, build some employees and use the collection built-in groupBy method to group them by their departments:

As you can see, Kotlin has some syntactic sugar that makes it less verbose than Java.

If you haven’t considered trying Kotlin yet, I think it is worth giving it a try.

Tags: , , , , , ,

35 programming habits that make your code smell

Interesting article about some bad programming practices, including topics like code organization, teamwork, testing and maintenance.

Tags: , , , ,

Converting a Map to a List in Java 8, Groovy and Ruby

Some days ago I was developing a task on a Gradle project and I faced with a situation where I had to convert a Map < String, List < String >> to List < Pair >, each pair containing the key and one element from the List.

I decided to compare the solution in three different languages: Java 8 (using lambdas and the Streams API), Groovy and Ruby to see how concise and expressive they would be. Then, I created the Groovy code and it looked like this:

Running the above code, the result is below:

The Ruby version looked like this:

The Ruby program generated the following output:

Below is the Java 8 version, using lambdas, Streams and the Collectors API:

Running the Java 8 version produced the following output:

The Groovy and Ruby version are very expressive and concise. Note the use of the collectMany method on the Groovy version and the use of the flatten method on the Ruby version to flatten the result list into a single list of pairs.
The Java 8 version made use of the collect method of the Stream API, to collect the results in a list of Pair instances, each one holding the key and value of each element from the List< String >.

What do you think about this comparison? Leave your comments here!

Tags: , , , , , , ,

JavaCodeKata – Lambdas

I’ve came across that kata from @brjavaman and @yanaga to teach lambdas, one of the new features of JDK 8.

There are some unit tests to validate the solution. I’ve found it a good opportunity to exercise the use of lambdas so I decided to solve it. Below is my solution to this kata.

The first method should take the String list and sort all the String elements in ascending (ASCII) order:

The other method should take the String list and:

  1. filter the elements that contains one or more digits
  2. transform (map) the remaining Strings into Integers
  3. sort the Integers in ascending order

The last method should take the String list and:

  1. filter the elements that contains one or more digits
  2. transform (map) the remaining Strings into Integers
  3. sort the Integers in descending order

Note that the steps filter the elements that contains one or more digits and transform (map) the remaining Strings into Integers are identical. So I decided to extract the partial Stream into a method with the Extract Method refactoring support on IntelliJ IDEA:

Then I refactored the the solution to use the new extracted method:

I re-run the tests and they all passed. What do you think about this solution? Do you suggest other ones?

K Palindromes puzzle

Here we have the K Palindromes puzzle from Javalobby:

You probably already know what a palindrome is: a string to results in the same word, whether read left to right, or right to left. A K Palindrome is when a string can be tranformed into a palindrome by changing K characters at most. Regular palindromes have K=0.

Your challenge today is to write a method which takes a string and a value for k and returns true if it the string qualifies as a K palindrome.

Below is the code in Ruby. Our input string is omississimo and it’s a 0 palindrome String.

The output is true. Do you have another solution? Drop your comments here!

Tags: , , , , , , ,

Minimum difference puzzle in Ruby

Folks, here we are for another puzzle from Javalobby:

Given two arrays, sorted and exactly the same length, write a function that finds a pair of numbers – one from each of the arrays – such that the difference between both is as small as possible.

Suppose our input arrays are [1,2,3,4,5] and [6,7,8,9,10]. Below is my solution in Ruby, it’s a one liner code :-):

The output is [5, 6].

Have another solution? Leave your comments here!

Tags: , , , , , , ,

Balancing arrays puzzle in Ruby

Here we are for another puzzle from Javalobby:

Given an array of numbers, return the index at which the array can be balanced by all numbers on the left side add up the the sum of all numbers of the right side.

For example, an array with [1,5,6,7,9,10] can be balanced by splitting the array at position 4

Here is the solution in Ruby:

The input array [1,5,6,7,9,10] will split the array at position 4, as stated above.

Any other solutions? Drop comments here 🙂

Tags: , , , , , , ,

Finding the second highest frequency

It’s been a long time since I posted for the last time, but I promise I’ll try to keep this blog up-to-date 🙂

One of the purposes of this blog is to explore new technologies and recently I’ve been studying Ruby solving some puzzles posted by on JavaLobby.

The problem is about finding the second highest frequency of a character in a String. Below is the Ruby code, using the powerful concept of Ruby closures.

For the input String "aabbbc", the result is "a". I could done it in a more OOP style, but I chose a more concise solution 🙂

If you have another version in Ruby, feel free to post a comment!

Tags: , , , , ,