Sunday 30 May 2021

Kotlin vs Java - String - Count lambda - Importance

In Kotlin we have count function which exactly provides the same output what we get in the length function.  here we have an overloading function too which takes predicate lambda (Char -> Boolean) as an input param.  

Lets see the below example and hope you will understand.  Here we are about to find the No. of times the character occurs in the string, will see the code snippet in both Kotlin and Java versions.

Kotlin: Type Inference and lambda expression.

val text = "Tester"
val findMe = 'e'
val count = text.count { it == findMe }
println("No. of $findMe in $text is $count")

Output: No. of e in Tester is 2

Java (Version< 8): In an optimized way, here we have written an extended logic by using recursive method and avoids the loops.  

  private static int countOccurences(String someString, char searchedChar, int index) {
        if (index >= someString.length()) {
            return 0;

        int count = someString.charAt(index) == searchedChar ? 1 : 0;
        return count + countOccurences(
                someString, searchedChar, index + 1);

long count = countOccurences("Tester",'e',0);

Output: 2

Java 8: Here the Lambda expression and filter function takes lambda expression and returns the IntStream and from that we can call IntStream functions, here data type has to be explicit and those not type inferences. 

String str="Tester";
char findMe='e';
long count = str.chars().filter(ch -> ch == findMe).count();

Output: 2

Code Snippet: In Kotlin this count function with predicate helps us on many things like password validation helpers  Please refer the below code . 

val password = "T1e st2er$#"
val digits = password.count { it.isDigit() }
val letters = password.count { it.isLetter() }
val lowercase = password.count { it.isLowerCase() }
val letterOrDigit = password.count { it.isLetterOrDigit() }
val uppercase = password.count { it.isUpperCase() }
val whiteSpaces = password.count { it.isWhitespace() }

println("Password: $password  ||| Length: ${password.count()}")
println("# of Digits: $digits")
println("# of Letters: $letters")
println("# of Lowercase char: $lowercase")
println("# of Letter or Digits: $letterOrDigit")
println("# of Uppercase char: $uppercase")
println("# of White Space: $whiteSpaces")


Password: T1e st2er$#  ||| Length: 11
# of Digits: 2
# of Letters: 6
# of Lowercase char: 5
# of Letter or Digits: 8
# of Uppercase char: 1
# of White Space: 1