Showing posts with label Collection. Show all posts
Showing posts with label Collection. Show all posts

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. 






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