Sunday, 13 June 2021

Kotlin Collection - zip & unzip function

zip function builds one new list of paired elements from two existing arrays. Zipping transformation is useful to combine two array values. The final result is equal to the length of the smaller array if both arrays have different size. The extra elements of the larger array are not included in the final list.

Similarly, to do the reverse transformation, i.e. unzipping, unzip() method is called. In this post, Please refer to the below code snippet for the same. 

In the below example we are associating the states with their corresponding registration code, and in the unzip we are doing reverse the things.   

Here, while doing the zip we are getting the list of pairs, and for the unzip we are using the destructuing it with two separate list of strings. 






Saturday, 12 June 2021

Get Initials for the Display name - String - Android (Kotlin)

This post explains to extract the initial for the display name, i.e. Wanna get the first character of the first two words from the string, below is my code snippet can any one help to optimize it?

For eg: 

Username                         Display initial 

Rajendra prasad guru     RP

Rahul                                 R

Gurunath Desigan            GD


See in the above code snippet, We had tried out the logic in multiple ways, i.e. with Sequence (line 3 to 12) and without sequence (14 to 19).   Here we have added println to see how the internal iteration works, while you are about to use please remove that print statement. 

As per my knowledge all the three are good and optimized in their own way. 

The first one is seems to be optimum, since the split itself has the limit of  2, so it takes only the first 2 split with delimiters. 

This second one adds one more extra function take(2) functions to the logic and it reduces the internal iteration before doing the map transformation function.

The third one is made it as very simple approach, which deals with the split function without sequences and it uses both limit and take function (take function used on the joinToString()'s transforming expression as lambda). 

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);
System.out.println(count);

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();
System.out.println(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")

Output: 

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

Sunday, 18 April 2021

Kotlin - Partition Function

Splits the original array / collections into pair of lists, where first list contains elements for which predicate yielded true, while second list contains elements for which predicate yielded false.

Please refer the below examples, here we used 2 filters to get the objects with certain crieteria, but it can be easily achieved through partition function, this executes the predicate and produce the pairs of list and we can access directly on pari's (first and second function) or we can destructure and use the same. 

data class Movies(val id: String,
                      val movieName: String,
                      val rating: Double = 1.0)

    val movies = listOf(Movies("100XA", "Guru", 4.5),
            Movies("100JK", "Ghab", 3.2),
            Movies("100HN", "Qualis", 1.2),
            Movies("1089O", "Tree"))

    // Using Filter
    println("### Rating Above 3 - Filter ###")
    movies.filter { it.rating > 3 }.forEach { println(it.movieName) }

    println("### Rating Not Above 3 - Filter ###")
    movies.filterNot { it.rating > 3 }.forEach { println(it.movieName) }

    // Using Partition - Destructuring the paris of list
    val (above3, notAbove3) = movies.partition { it.rating > 3 }
    println("\n### Rating Above 3 - Partition  ###")
    above3.forEach { println(it.movieName) }

    println("### Rating Not Above 3 - Partition  ###")
    notAbove3.forEach { println(it.movieName) }

Output:

### Rating Above 3 - Filter ###
Guru
Ghab
### Rating Not Above 3 - Filter ###
Qualis
Tree

### Rating Above 3 - Partition  ###
Guru
Ghab
### Rating Not Above 3 - Partition  ###
Qualis
Tree

Sunday, 7 March 2021

Kotlin Collection - Mathematic Sets Specific Operation - Union, Intersection & Subract

The Kotlin collections package contains extension functions for popular operations on sets: finding intersections, merging, or subtracting collections from each other.

To merge two collections into one, use the union() function. It can be used in the infix form a union b. Note that for ordered collections the order of the operands is important: in the resulting collection, the elements of the first operand go before the elements of the second.

To find an intersection between two collections (elements present in both of them), use intersect(). To find collection elements not present in another collection, use subtract(). Both these functions can be called in the infix form as well, for example, a intersect b

Code Snippet:

val universityDefCenters = listOf("Delhi", "Mumbai","Puducherry","Chennai")
val universitySouthCenters = listOf("Karnataka", "Puducherry","Chennai", "Kerala")

val allCenters= universityDefCenters union universitySouthCenters
val commonCenters = universityDefCenters intersect universitySouthCenters
val nonSouthCenters = universityDefCenters subtract universitySouthCenters

println("All Centers (Union): $allCenters")
println("Common Centers (Intersection): $commonCenters")
println("Non-South Centers (Subtract): $nonSouthCenters")

Output:
All Centers (Union): [Delhi, Mumbai, Puducherry, Chennai, Karnataka, Kerala]
Common Centers (Intersection): [Puducherry, Chennai]
Non-South Centers (Subtract): [Delhi, Mumbai]


Sunday, 6 December 2020

Kotlin - Collection Partition function

Splits the original array / collection into pair of lists, where first list contains elements for which predicate yielded true, while second list contains elements for which predicate yielded false.  
Please refer the below Code Snippet for the details.

val employeeList = listOf(
EmployeeInfo("HB100", "Ragavan A", 30),
EmployeeInfo("AX782", "Peter J", 54),
EmployeeInfo("ZD242", "Karlos V", 56),
EmployeeInfo("CD902", "Ismail N", 24)
)

val (ageAbove50, ageBelow50) = employeeList.partition { it.eAge > 50 }
println("\nEmployee List: $employeeList")
println("\nAge Above 50: $ageAbove50")
println("\nAge Below 50: $ageBelow50")

/*Since it returns as pairs, If we want to ignore the other condition i.e. 
ageBelow50 employees use _*/
val (ageAbove50Plus, _) = employeeList.partition { it.eAge > 50 }
println("\nAge 50+: $ageAbove50Plus")

Output:

Employee List: 
[EmployeeInfo(eId=HB100, eName=Ragavan A, eAge=30), 
EmployeeInfo(eId=AX782, eName=Peter J, eAge=54), 
EmployeeInfo(eId=ZD242, eName=Karlos V, eAge=56), 
EmployeeInfo(eId=CD902, eName=Ismail N, eAge=24)]

Age Above 50: [EmployeeInfo(eId=AX782, eName=Peter J, eAge=54), 
EmployeeInfo(eId=ZD242, eName=Karlos V, eAge=56)]

Age Below 50: [EmployeeInfo(eId=HB100, eName=Ragavan A, eAge=30), 
EmployeeInfo(eId=CD902, eName=Ismail N, eAge=24)]

Age 50+: [EmployeeInfo(eId=AX782, eName=Peter J, eAge=54), 
EmployeeInfo(eId=ZD242, eName=Karlos V, eAge=56)]

Sunday, 17 May 2020

lateinit Vs by lazy


Both "lateinit" and "by lazy" are Kotlin Property initializers.

lateinit:
  • Use it with mutable variable [var]
  • Allowed with only non-nullable data types
  • This modifier is not allowed on properties of primitive types
  • It is a promise to compiler that the value will be initialized in future.
  • If you try to access lateinit variable without initializing it then it throws UnInitializedPropertyAccessException.
by lazy:
  • Lazy initialization was designed to prevent unnecessary initialization of objects.
  • Your variable will not be initialized unless you use it.
  • It is initialized only once. Next time when you use it, you get the value from the memory.
  • It is thread safe (It initializes in the thread where it is used for the first time. Other threads use the same value stored in the cache).
  • The variable can only be val.
  • The variable can only be non-nullable.
class Basic {
    private lateinit var strMsg: String
    private val strMsg1: String by lazy {
        println("Lazy Initializing - Variable born")
        return@lazy "Tester"
    }

    fun initBasic() {
        //Late Initialization - Check
        println("strMsg initialization status is ${::strMsg.isInitialized}");
        strMsg = "Testing"
        println("strMsg value is $strMsg, now the initialization status is ${::strMsg.isInitialized}");

        //Lazy Initialization - Check
        println("strMsg1 value is ${strMsg1}");
    }
}

fun main(ar: Array<String>) {
    Basic().initBasic()
}

Console Output:

strMsg initialization status is false
strMsg value is Testing, now the initialization status is true
Lazy Initializing - Variable born
strMsg1 value is Tester