Search code examples
androidlistkotlindata-class

Access a Data Class Variable that's Being Stored in List - Kotlin


I have a data class which takes in A LOT of variables. The object of this class is then stored in a mutable list. How do I search for the object that contains a specific user entered value and then return the associated variables of that object? For example, the user enters that they want to view variable d where variable a == "test" so I need to search the list to find the object where variable a equals "test" and then return the value of variable d of that object.

Below is example of code of what I currently have:

var exampleList = mutableListOf<Any>()

data class Example(val a: String, val b: String, val c: String, val d: String, val e: String,
               val f: String,val g: String, val h: String, val i: String, val j: String, val k: String,
               val l:String, val m: String, val n:String, val q: String, val r: String,
               val s: String, val t: String, val u: String, val v: String, val w: String,
               val x: String, val y: String, val z: String, val aa: String, val bb: String,
               val cc: String, val dd: String, val ee: String, val ff: String,
               val ruptureDisc: String, val ruptureDiscNotes: String, val remote: String, val gg: String,
               val hh: String, val ii: String, val jj: String, val kk: String, val ll: String,
               val mm: String, val nn: String, val oo: String, val pp: String, val qq:String,
               val rr: String)

fun addToList() {
        exampleList.add(
            Example(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
                12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
                23, 24, 25, 26, 27, 28, 29, 30,
                31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
                41, 42, 43, 44, 45)
        )
}

Solution

  • filter seems like a natural choice in this case, if you want to get items based on a certain conditions.

    data class Example(val a: String, val b: String, val c: String, val d: String, val e: String)
    var exampleList = mutableListOf<Example>()
    
    fun addToList() {
        exampleList.add(Example("test", "2", "3", "4", "5"))
        exampleList.add(Example("1", "2", "3", "4", "5"))
    }
    
    addToList()    
    val filteredList = exampleList.filter { it.a == "test" }