Sunday, 22 August 2021

Deduplicating Collection Items

Deduplication refers to a method of eliminating a dataset's redundant data, here in Kotlin we normally use the toSet() function to get the unique datasets, now the distinct() and distinctBy{} joins the club. Please refer the below code snippet for more details, the below example uses both primitive typed object and data class object (Be careful on the data order, this will give an impact).

data class Tez(val id: String)

val users = listOf("AAA", "aaa", "BBB", "bbb", "CCC", "ccc", "AAA", "aaa", "BBB", "bbb", "CCC", "ccc")
    val tezUsers = listOf(
        Tez("AAA"),
        Tez("aaa"),
        Tez("BBB"),
        Tez("bbb"),
        Tez("CCC"),
        Tez("ccc"),
        Tez("AAA"),
        Tez("aaa"),
        Tez("BBB"),
        Tez("bbb"),
        Tez("CCC"),
        Tez("ccc")
    )
    println("toSet: ${users.toSet()}")
    println("Data Object toSet: ${tezUsers.toSet()}")
    println("distinct : ${users.distinct()}")
    println("Data object distinct: ${tezUsers.distinct()}")
    println("distinctBy: ${users.distinctBy { it.lowercase() }}")
    println("Data object distinctBy: ${tezUsers.distinctBy { it.id.lowercase() }}")

    val revUsers = users.reversed()
    val revTezUsers = tezUsers.reversed()
    println("\n\nreversed toSet: ${revUsers.toSet()}")
    println("reversed Data object toSet: ${revTezUsers.toSet()}")
    println("reversed Distinct : ${revUsers.distinct()}")
    println("reversed Data object distinct: ${revTezUsers.distinct()}")
    println("reversed object distinctBy: ${revUsers.distinctBy { it.lowercase() }}")
    println("reversed Data object distinctBy: ${revTezUsers.distinctBy { it.id.lowercase() }}")

Output:

toSet: [AAA, aaa, BBB, bbb, CCC, ccc]
Data Object toSet: [Tez(id=AAA), Tez(id=aaa), Tez(id=BBB), Tez(id=bbb), Tez(id=CCC), Tez(id=ccc)]
distinct : [AAA, aaa, BBB, bbb, CCC, ccc]
Data object distinct: [Tez(id=AAA), Tez(id=aaa), Tez(id=BBB), Tez(id=bbb), Tez(id=CCC), Tez(id=ccc)]
distinctBy: [AAA, BBB, CCC]
Data object distinctBy: [Tez(id=AAA), Tez(id=BBB), Tez(id=CCC)]


reversed toSet: [ccc, CCC, bbb, BBB, aaa, AAA]
reversed Data object toSet: [Tez(id=ccc), Tez(id=CCC), Tez(id=bbb), Tez(id=BBB), Tez(id=aaa), Tez(id=AAA)]
reversed Distinct : [ccc, CCC, bbb, BBB, aaa, AAA]
reversed Data object distinct: [Tez(id=ccc), Tez(id=CCC), Tez(id=bbb), Tez(id=BBB), Tez(id=aaa), Tez(id=AAA)]
reversed object distinctBy: [ccc, bbb, aaa]
reversed Data object distinctBy: [Tez(id=ccc), Tez(id=bbb), Tez(id=aaa)]

Please refer the above highlighted output, produces the different output due to dataset order.  Also, in the lambda it.lowercase() that won't change the dataset value, it just use for the comparison purpose only.  

Happy Coding :-)

Saturday, 17 July 2021

Capitalize each word of a String in Kotlin

capitalize() the string extension function is got deprecated from Kotlin 1.5 and they have provided an alternative as replaceFirstChar().  Since I'm creating a new extension functon and performing the logic to capitalize the words in the sentence.  We have used Regex() param to the split function, inorder to remove the unnecessary spaces at the end of each words.  In case you are not going to remove those spaces, so you can simply use .split(" ")

fun String.capitalizeWord() = lowercase()
    .split("\\s+".toRegex())
    .joinToString(" ") {
        it.trim().replaceFirstChar(Char::titlecase)
    }

println("thE QuIck    bROwN   FOx".capitalizeWord())
println("thE qUiCk bRown FoX".capitalizeWord())

Output:

The Quick Brown Fox
The Quick Brown Fox

Happy Coding :-)

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

Monday, 27 April 2020

Kotlin Generic function & Infix

Generics are the powerful features that allow us to define classes, methods and properties which are accessible using different data types while keeping a check of the compile-time type safety.

A generic type is a class or method that is parameterized over types. We always use angle brackets (<>) to specify the type parameter in the program.

Advantages of generic –
  1. Type casting is evitable- No need to typecast the object.
  2. Type safety- Generic allows only single type of object at a time.
  3. Compile time safety- Generics code is checked at compile time for the parameterized type so that it avoids run time error
Infix:  This is the Kotlin keyword used before the function and this enables us to call the methods without any dot and parenthesis.  This increase the code readability in a general way (as like as speaking language :-) ).

Rules for the Infix:
  1. All Infix functions are need to be Extension function or member function.
  2. It must accept only one param and no default value is permitted.
  3. It must have "infix" keyword before to the function.  
Lets see some code Snippet: 
  1. Just created a demo data class 
  2. Two Generic and extension functions (Extension of List) and in that one of them is infix, you can see the above rules is applied.  
data class Demo(val id: String, val name: String)

fun <T> List<T>.updateObjWith(other: List<T>) = this + other

infix fun <T> List<T>.updateWith(other: List<T>) = this + other

Calling the non-infix generic function:
  1. Here you can see the list objects created for different types
  2. Updated the object with the some more contents using the updateObjWith(<T?) method 
fun main() {
    val myPlaces = listOf<String>("Chennai", "Puducherry")
    val myPlayers = listOf<Demo>(Demo("123EAX", "Ragavan"), Demo("989XEA", "Rajeevan"))
    val myNumbers = listOf<Int>(1, 2, 3, 4, 5)

    val updatedPlayers: List<Demo> = myPlayers.updateObjWith(listOf(Demo("325EUV", "Manirathnam")))
    updatedPlayers.forEach { println(it) }

    val updatedPlaces: List<String> = myPlaces.updateObjWith(listOf("Madurai"))
    updatedPlaces.forEach { println(it) }

    val updatedNumbers = myNumbers.updateObjWith(listOf(10, 9, 8, 7, 6))
    updatedNumbers.forEach { println(it) }
}

Calling via Infix function: Code will be in more readable form.

fun main() {
    val myPlaces = listOf<String>("Chennai", "Puducherry")
    val myPlayers = listOf<Demo>(Demo("123EAX", "Ragavan"), Demo("989XEA", "Rajeevan"))
    val myNumbers = listOf<Int>(1, 2, 3, 4, 5)

    val updatedPlayers = myPlayers updateWith listOf(Demo("325EUV", "Manirathnam"))
    updatedPlayers.forEach { println(it) }

    val updatedPlaces = myPlaces updateWith listOf("Madurai")
    updatedPlaces.forEach { println(it) }

    val updatedNumbers = myNumbers updateWith listOf(10, 9, 8, 7, 6)
    updatedNumbers.forEach { println(it) }
}

Sunday, 5 April 2020

Singleton - Java vs Kotlin

Singleton is a widely used design pattern in our programming, because the single instance or object reference has been used to accessing their properties and that instance remains through out the  application session.

Now we can see how it will be implemented in Java and Kotlin.

Singleton Using Java:

public final class Singleton {
    private static final Singleton INSTANCE = new Singleton();
    public String property1;

    private Singleton() {
    }

    public static Singleton getInstance() {
        return INSTANCE;
    }

    public String getInfo() {
        return "SingleInfo";
    }
}

Points to be remembered on creating the Singleton class using Java.
  1. Class need to be final, in order to avoid this class to be inheritance by other.
  2. Constructors are need to be private
  3. private, static and final instance have to instantiated.
Accessing the properties and methods will be as follows.

String property1 = Singleton.getInstance().property1;
String info = Singleton.getInstance().getInfo();

Singleton in Kotlin: Here it is very crazy in kotlin, the below things does the job.

object Singleton {
    var property1: String? = null
    val info: String
        get() = "SingleInfo"
}


val property = Singleton.property1
val info = Singleton.info

Happy Coding :-)

Monday, 27 January 2020

Kotlin Complete References

The below reference links are enough for us to get a good amount of knowledge on Kotlin Programming. 


📌 Highly Recommended   |  
🔖 Recommended

Kotlin Cheat Sheet:
📌 Kotlin Academy

Kotlin Videos:
General Videos 
📌 Smarthed Kotlin Playlist
🔖 Telusko Kotlin Playlist
📌 CodingWithMitch for Kotlin Coroutines 
 
Videos by Dr. Venkat Subramaniam 
📌 Kotlin for Java Programmers 
🔖 Kotlin for Java Programmers 
📌 Kotlin Programming
📌 Functional Programming in Kotlin
🔖 Exploring Coroutines in Kotlin

Videos by Hadi Hariri
📌 Kotlin Beyond the basis
📌 Functional Programming with kotlin
📌 Kotlin Coroutines

Web Tutorials:
📌 Programiz
📌 GeeksForGeeks
🔖 TutorialKart


Sunday, 15 September 2019

Kotlin Code to break forEach inline loops

In General we are unable to break the forEach inline loops.  Please check the below tries and see the proper way to do so.

1
2
3
4
5
6
7
8
9
 var data = listOf<String>("Dev", "Prd", "Test", "Sbx", "demo")
    data.forEach {
        if (it.equals("Prd")) {
            println("I'm Selected $it")
            return
        }
        println("I'm in the list $it")
    }
    println("Done")

the above code produces the below output, if we use "return" on the line 5 we will be getting the below output, because that will abundantly break and come out of the method.  You can see the "Done" is not printed.

I'm in the list Dev
I'm Selected Prd

Hence to resolve we can try out with the label concept available in kotlin,  Since our programming language says there is no explicit label needed for the inline function. we can directly use it as "return@forEach".  But this will also lead to be failed, this produces the below output.

I'm in the list Dev
I'm Selected Prd
I'm in the list Test
I'm in the list Sbx
I'm in the list demo
Done

The highlighted text are unnecessary to this case.  In the below code snippet run block with label is used to break the loop as soon as we get the expected result and breaks the blocks and proceeds the normal flow function flow.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
var data = listOf<String>("Dev", "Prd", "Test", "Sbx", "demo")
    run envBlock@{
        data.forEach {
            if (it.equals("Prd")) {
                println("I'm Selected $it")
                return@envBlock
            }
            println("I'm in the list $it")
        }
    }
    println("Done")

And will get the expected output.


I'm in the list Dev
I'm Selected Prd
Done

Happy Coding :-)

Saturday, 17 August 2019

Kotlin Null Handling


- Kotlin Null Safe
- Here we can’t initialise or assign null value.
- If purposely we need to have null, it provides with Question mark.

val username: String? = null

Here we have 4 types of null handling shots.

1. Safe Call
2. Safe Call with let
3. Elvis Operator
4. Non-Null Assertion Operator.

1. Safe Call: It is represented by "?." and this facilitates to access the methods of the object.  In case the reference object or variable is null it will safely handle that and produce the return value as string as "null"

var username: String? = null
println("Username Length is : ${username?.length}")   // We won't get crash, it just print the value as null
username = "manakular"
println("Username Length is : ${username?.length}")

Output:


Username Length is : null
Username Length is : 9

2. Safe Call with let:  It is also similar to the Safe call, instead of accessing the method this allows you to execute the block of code and implicitly returns the last line of the block based on the code,  here "it" keyword will refer the concern data value.

    var username: String? = "manakularpondy"
    val status: String? = username?.let {
        println("Username is $it")
        if (it.length > 10) "Valid Input" else "Invalid length"
    }
    println(status)

Output:

Username is manakularpondy
Valid Input

In case, if we change the value to null  var username: String? = null  the status value will be also null.  So, in order to handle the failure i.e. null scenario we can take help of run block.


    var username: String? = null
    val status: String? = username?.let {
        println("Username is $it")
        if (it.length > 10) "Valid Input" else "Invalid length"
    }.run {
        "Need Input"
    }
    println(status)

Output:

Need Input

3. Elvis Operator: Hope we most of them aware we don't have ternary operator in kotlin programming, but similar to that we are having this elvis operator.  This will be denoted by ?: as mentioned on the below code snippet the username is initialised as null and once we trying to access the length of the variable we are all aware it going to be a null type.   Hence so we are accessing the username value via Safe call (?), then it sees the value as null our elvis operator helps to executes the or take the values after the ?:  Hence here we can see the length value as  0 even the username value is null.    

var username: String? =null
val length: Int = username?.length ?: 0
println("Length is $length")

Output:

Length is 0

4. Non-Null Assertion Operator: This need to handled very carefully, it is referred by using the double exclamation (!!).   Since you are 100% sure the object is non-null then you can use this else the value is null it will throws the null pointer exception.


var username: String? =null
val length: Int = username!!.length ?: 0
println("Length is $length")

The above code snippet throws the null pointer exception, because username object is null

Saturday, 20 July 2019

Kotlin Code - Get IPV4 & IPV6 Address

The below code helps to get the IPv4 and IPv6 Address using Kotlin.

import java.net.NetworkInterface
import java.util.*

/*
* Author: Rajendhiran E
* Date: 21-Jan-2018
* */

object IPHelper {
    val IPV4Address: String
        get() = getIPAddress(true)

    val IPV6Address: String
        get() = getIPAddress(false)

    /**
     * Get IP address from first non-localhost interface
     * @param userIPV4 true=return ipv4, false=return ipv6
     * @return address or empty string
     */
    private fun getIPAddress(userIPV4: Boolean): String {
        try {
            Collections.list(NetworkInterface.getNetworkInterfaces()).forEach {
                Collections.list(it.inetAddresses).forEach {
                    if (!it.isLoopbackAddress) {
                        val sAddr = it.hostAddress
                        val isIPv4 = sAddr.indexOf(':') < 0
                        if (userIPV4) {
                            if (isIPv4) {
                                return sAddr
                            }
                        } else {
                            if (!isIPv4) {
                                val delim = sAddr.indexOf('%')
                                return if (delim < 0) sAddr.toUpperCase() else sAddr.substring(0, delim).toUpperCase()
                            }
                        }
                    }
                }
            }
        } catch (ignored: Exception) {
        }
        return ""
    }
}


println("IP Address V4 - ${IPHelper.IPV4Address}")
println("IP Address V6 - ${IPHelper.IPV6Address}")


Output  Console
IP Address v4 - 192.168.240.2
IP Address v6 - FE80:0:0:0:4D9:5C92:3433:8A6B

Happy Coding :-)