Home > Back-end >  Convert two string list to List of Object use first list index to get the value from Second list
Convert two string list to List of Object use first list index to get the value from Second list

Time:10-02

I am slightly confused to get the List of object from two lists of string using map.

Let's take an example: List 1:

var name = arrayListOf("name1","name2","name3")

List 2:

var lastName = arrayListOf("lastName1","lastName2","lastName3")

The data class of Names as below

data class Names(
var name: String, 
var lastName: String
)

Now i want the List which is combination of name and lastName where we use the name index to get the lastName.

The list of Names as output is below:

[Names(name=name1, lastName=lastName1), Names(name=name2, lastName=lastName2), Names(name=name3, lastName=lastName3)]

Request to use the rx kotlin function. By using collection it is easy to solve.

CodePudding user response:

This is a zip operation:

var name = arrayListOf("name1","name2","name3")
var lastName = arrayListOf("lastName1","lastName2","lastName3")
data class Names(
var name: String, 
var lastName: String
)
fun main() {
    println(name.zip(lastName) {n, f -> Names(n, f)} )
}

output

[Names(name=name1, lastName=lastName1), Names(name=name2, lastName=lastName2), Names(name=name3, lastName=lastName3)]

(I don't think you need 'reactive' programming to do this)

  • Related