Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter nested list with kotlin

Tags:

kotlin

Ques: I want to filter list within a list. All of my data models are immutable.

My JSON structure looks like this

{
  "root": [
    {
      "id": 2,
      "val": 1231.12,
      "fruit": [
        {
          "id": 2,
          "name": "apple"
        }
      ]
    },
    {
      "id": 3,
      "val": 1231.12,
      "fruit": [
        {
          "id": 2,
          "name": "apple"
        },
        {
          "id": 3,
          "name": "orange"
        }
      ]
    }
  ],
  "fruits": [
    {
      "id": 1,
      "name": "apple"
    },
    {
      "id": 2,
      "name": "guava"
    },
    {
      "id": 3,
      "name": "banana"
    }
  ]
}

Problem Statement - Basically, I want to create a list of all items of root where fruit name is apple. Currently, my naive solution looks like this. This involves creating a temporary mutuable list and then add specific items to it.

Below solution works fine but is there any other better way to achieve the same.

val tempList = arrayListOf<RootItem>()

root?.forEach { item -> 
    item.fruit.filter {
        // filter condition
        it.id != null && it.name == "apple"
    }
    testList.add(item)
}
like image 576
user3354265 Avatar asked Nov 05 '25 04:11

user3354265


1 Answers

A combination of filter and any will do the work:

val result = root?.filter { item -> 
    item.fruits.any { it.id != null && it.name == "apple" } 
}

BTW: Your solution will not work. The filter function does return a new list, that you are not using. And you always add the item to the list, not only if the predicate returns true.

like image 120
Rene Avatar answered Nov 09 '25 08:11

Rene



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!