Home > Software engineering >  Is there any efficient way to search throughout a list of objects every field?
Is there any efficient way to search throughout a list of objects every field?

Time:07-28

Let's say I have an object

data class Person(
   val name: String,
   val surname: String,
   val street: String,
   val postalCode: String,
   val telephoneNumber: String,
)

And then I have a list of persons :

val personsList = listOf(
  Person(name="John", surname="Hams", street="Gariolg", postalCode="929429", telephoneNumer=" 2142422422",),
Person(name="Karl", surname="Hamsteel", street="Gariolg", postalCode="124215", telephoneNumer=" 3526522",),
Person(name="Stepf", surname="Hiol", street="Bubmp", postalCode="5342", telephoneNumer=" 7574535",),
Person(name="Germa", surname="Foo", street="Hutioa", postalCode="235236", telephoneNumer=" 112355",)
)

So now if the user types for instance Hams it should return John and Karl, because both have the word "Hams" inside the object. What I mean is doesn't matter if the user types postalCode, name, or whatever I'd like to loop throughout the object to check if there's any coincidence.

CodePudding user response:

How i would do it, is create a function inside the data class, say, for example, like this. This will check if any field inside your data class matches with the given string.

In my example i check if whole string matches, but you can change this however you want. You probably want it.contains(searchString) inside the any block.

fun checkIfStringMatches(searchString: String) : Boolean =
    listOf(this.name, this.surname, this.strees, this.postalCode, this.telephone).any { it == string }

Then, you can use this function on your list of persons to filter if any object matches your string search.

personList.filter{it.checkIfStringMatches(mySearchString)} // this will return a list with all the objects that match your search criteria

The problem is that if you add more fields, you will have to change this function and add it to the listOf() block. But i don't know any way to do this automatically without reflection, which is not really recommended to use. If you still want to use it, here is a question on this topic. Kotlin: Iterate over components of object

CodePudding user response:

Try this, it will work.

 personsList.filter { it.surname.startsWith("Hams") }.map {
                Log.d("filter_name", it.name) 
            }

CodePudding user response:

Hey You can apply filter method on list and grab the expected output like below :

val filtered = personsList.filter { it.toString().contains("Hams", true) } 
  • Related