The power of Java lambda expressions
Use lambdas whenever possible
In this story, I will demonstrate how much are powerful Java lambda expressions. In most cases, you can do your job in just one line of code! Let’s imagine you have the next task to do:
You are given a string
word
that consists of digits and lowercase English letters.You will replace every non-digit character with a space. For example,
"a123bc34d8ef34"
will become" 123 34 8 34"
. Notice that you are left with some integers that are separated by at least one space:"123"
,"34"
,"8"
, and"34"
.Return the number of different integers after performing the replacement operations on
word
.Two integers are considered different if their decimal representations without any leading zeros are different.
Here is the solution and explanation is just below Java code:
Programming is just putting objects from one state to another. Here is how you can make a solution with just one line of code using a few transformations:
word.replaceAll("[a-z]+", " ")
- We replace all successive letters with space. So we have numbers split with spaces. replaceAll() returns just one String.word.replaceAll("[a-z]+", " ").split(" ")
- We split numbers into an array of numbers (as string array). The first and last elements can be empty strings if we had space on the beginning or end of the stringword.replaceAll("[a-z]+", " ")
Arrays.stream(word.replaceAll("[a-z]+", " ").split(" "))
- convert the array into the stream of elements.filter(s -> !"".equals(s))
- removes possibly empty strings on the beginning or end of string stream.map(s -> s.replaceFirst("^0+", ""))
- transforms numbers (as strings) into strings without leading zeros. This is what tells regex^0+
. We remove just the first occurrence of this because there is just one beginning of the string :-). replaceAll() would also work..collect(Collectors.toSet())
- makes set from string stream. Duplicates are eliminated because this is set.size()
- The size of the set is number of different numbers
We didn’t use Long.parseLong() or Integer.parseInt() because a number of digits in a number can be quite big and we would have exceptions. Because of that, we have used a set of strings.
That’s all folks! If you like the story, please follow me.