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

No comments: