Home > Blockchain >  Combining Two List in Kotlin with Index
Combining Two List in Kotlin with Index

Time:04-19

There is a data class as fruits.

data class Fruits(
    val code: String, //Unique
    val name: String
)

The base list indexed items with boolean variable is as below.

val indexList: MutableList<Boolean> = MutableList(baseFruitList.size) { false }

Now the Favourite Indexed list is as below

val favList: MutableList<Boolean> = MutableList(favFruitList.size) { true}

I want a combined full list which basically has the fav item indicated as true.

Ex: 
baseFruitList = {[FT1,apple],[FT2,grapes],[FT3,banana],[FT4,mango],[FT5,pears]}
favList = {[FT2,grapes],[FT4,mango]}

The final index list should have

finalIndexed = {false,true,false,true,false}

How can we achieve in Kotlin, without iterating through each element.

CodePudding user response:

You can do

val finalIndexed = baseFruitList.map { it in favList }

assuming, like @Tenfour04 is asking, that name is guaranteed to be a specific value (including matching case) for a specific code (since that combination is how a data class matches another, e.g. for checking if it's in another list)

If you can't guarantee that, this is safer:

val finalIndexed = baseFruitList.map { fruit ->
    favList.any { fav.code == fruit.code }
}

but here you have to iterate over all the favs (at least until you find a match) looking to see if one has the code.

But really, if code is the unique identifier here, why not just store those in your favList?

favList = listOf("FT2", "FT4") // or a Set would be more efficient, and more correct!
val finalIndexed = baseFruitList.map { it.code in favList }

I don't know what you mean about "without iterating through each element" - if you mean without an explicit indexed for loop, then you can use these simple functions like I have here. But there's always some amount of iteration involved. Sets are always an option to help you minimise that

  • Related