Home > Enterprise >  how to update a list by an other list of the same type on kotlin
how to update a list by an other list of the same type on kotlin

Time:06-09

I have 2 list of Skill object.

AllSkills represent the full list of skills that can be found in the app. UserSkills represent the skills that the user has on his account.

What I want to do is to replace any skill in AllSkill that exist in UserSkill (having the same id) by the skill of UserSkill,

But I don't understand how to do it, can someone help me pls ?

Exemple:

val allSkills = listOf<Skill>(Skill(id = 0, note = null), Skill(id =0, note = null)
val userSkills = listOf<Skill>(Skill(id = 1, note = 2)

then the result I want is :

val result = listOf<Skill>(Skill(id = 0, note=null, Skill(id = 1, note = 2)

-> The skill contained in userSkill (id = 1) as the note of the userSkill

CodePudding user response:

You can transform the user skills into a Map<Int, Skill> by associating them with the ID and proceed with replacing allSkills if it exists in such map.

Haven't tested it but it could look like this:

val allSkills = listOf<Skill>(Skill(id = 0, note = null), Skill(id =0, note = null)
val userSkills = listOf<Skill>(Skill(id = 1, note = 2)

val userSkillsMap = userSkills.associateBy { it.id }


// userSkillsMap[skill.id] returns the skill if it exists
// userSkillsMap[skill.id] returns null if it doesnt exist
// With the ?: (elvis operator) we default back to the present skill
val allSkillsUpdated = allSkills.map { skill -> userSkillsMap[skill.id] ?: skill }

CodePudding user response:

data class Skill(
  val id: Int,
  val note: Int?
)

val allSkills = listOf(
  Skill(id = 0, note = null),
  Skill(id = 1, note = null)
)

val userSkills = listOf(
  Skill(id = 1, note = 2)
)

val result = allSkills
  .map { allSkill ->
    userSkills
      .firstOrNull { userSkill -> userSkill.id == allSkill.id } ?: allSkill
  }

Note that for large skill lists @SomeRandomITboy's solution will most probably be faster.

  • Related