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).