4

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)
}

1 Answer 1

24

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.

Sign up to request clarification or add additional context in comments.

1 Comment

How would we do if we want only to remove the fruit items that doesn't contain 'apple' ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.