Search code examples
androidkotlindata-class

How to filter ArrayList<myDataClass> through only one item type of that data-class in Kotlin?


I'm new to this. Is it possible to filter ArrayList's "one part"?

In my UserDto.kt file I have defined my data class:

data class  UserDto (val mainWordSplit: String, val defnSplit: String)

Now in my MainActivity.kt file I have created ArrayList with UserDto type and put things inside:

private var enPairs = ArrayList<UserDto>()
...
var onePair = UserDto(mainWordSplit, defnSplit)
enPairs.add(onePair)

where mainWordSplit and defnSplit are Strings.

Now I want to filter through "enPairs" considering only "mainWordSplit" part of the list. Do I have to make another list of only mainWordSplit items, filter it and then remember indexes or is there another way?


Solution

  • Kotlin has a extension function that you can use - filter

    Here's an example:

    enPairs.filter { it.mainWordsSplit == "whatever you want to keep " }