Home > Software design >  find a class item in array in Kotlin
find a class item in array in Kotlin

Time:09-27

I have arraylist class and want to find the person inside

 val personlist : ArrayList<Person>
 
 personlist.add("Max","Mustermann","24")
 
 val searchingfield = searchEt.text.toString()
 
 val foundNames = personlist.filter { it.startsWith(searchingfield)}

Looking for smth smilar to this.

I want to find the person inside of the array list, with his name, surname or age, when I clicked the search button

CodePudding user response:

So when you are doing a filter on personList the it in the lambda refers to any individual element in personList - so that would be of type Person.

Person is not going to have a startsWith function unless you've defined one. You will probably need to look at the fields. For example, if it has surname and you just want to compare by equality, you would do something like this:

val foundNames = personlist.filter {
    it.surname == searchingfield
}

You can also rename the lambda parameter to something more clear:

val foundNames = personlist.filter { person ->
    person.surname == searchingfield
}

The contents of the lambda is up to you, just know that it is a Person and not a String.

CodePudding user response:

you can try this

val foundNames = personlist.filter {
it.name == searchingfield || it.surname == searchingfield || it.age == searchingfield }
  • Related