glomowa
glomowa

Reputation: 21

Comparing elements from 2 list kotlin

im having 2 list of different variable, so i want to compare and update the 'Check' value from list 2 if the 'Brand' from list 2 is found in list 1

--------------------    --------------------    
| Name   | Brand   |    | Brand    | Check |
--------------------    -------------------- 
| vga x  | Asus    |    | MSI      |   X   |
| vga b  | Asus    |    | ASUS     |   -   |
| mobo x | MSI     |    | KINGSTON |   -   |
| memory | Kingston|    | SAMSUNG  |   -   | 
--------------------    -------------------- 

so usually i just did

for(x in list1){
  for(y in list2){
     if(y.brand == x.brand){
        y.check == true
     }
  }
}

is there any simple solution for that?

Upvotes: 0

Views: 481

Answers (2)

Bram Van Dyck
Bram Van Dyck

Reputation: 139

data class Item(val name: String, val brand: String)

fun main() {
    val list1 = listOf(
        Item("vga_x", "Asus"),
        Item("vga_b", "Asus"),
        Item("mobo_x", "MSI"),
        Item("memory", "Kingston")
    )
    
     val list2 = listOf(
        Item("", "MSI"),
        Item("", "ASUS"),
        Item("", "KINGSTON"),
        Item("", "SAMSUNG")
    )
    
    // Get intersections
    val intersections = list1.map{it.brand}.intersect(list2.map{it.brand})
    println(intersections)
    
    // Returns => [MSI]
    
    // Has any intersections
    val intersected = list1.map{it.brand}.any { it in list2.map{it.brand} }
    println(intersected)
    
    // Returns ==> true
    
}

UPDATE: I just see that this isn't a solution for your problem. But I'll leave it here.

Upvotes: 0

Tenfour04
Tenfour04

Reputation: 93581

Since you're mutating the objects, it doesn't really get any cleaner than what you have. It can be done using any like this, but in my opinion is not any clearer to read:

    list2.forEach { bar ->
        bar.check = bar.check || list1.any { it.brand == bar.brand }
    }

The above is slightly more efficient than what you have since it inverts the iteration of the two lists so you don't have to check every element of list1 unless it's necessary. The same could be done with yours like this:

    for(x in list2){
        for(y in list1){
            if(y.brand == x.brand){
                x.check = true
                break
            }
        }
    }

Upvotes: 1

Related Questions