0

I have a list like below,

ThreadsList-
    Thread1-
       Messages-
         Message1
           text="@"
         Message2
           text="hello"
    Thread2-
       Messages-
         Message1
           text="@"
         Message2
           text="hello"
         Message3
           text="hi"

I need to remove all messages inside each Thread that has the text "@"

I have tried the below code but it's not working as expected,

threadsList.filter { item ->
            item.messages.any { !it.text.equals("@")  }
        }
1
  • use Messages1 instead of any. Commented Feb 11, 2021 at 8:12

2 Answers 2

1

What you have done by your code is to filter out the threads that contains all messages with text @. Since you have applied the filter method on threadsList, you will get a output threadsList in which all threads contains at least a non-@ message.

Now, what you have to do is perform some operation on all threads in the threadsList to filter out the messages with @ in it. It looks like this :

threadsList.onEach { thread ->
            thread.messages.filter { message ->
                message.text != "@"
            }
        }

and this will returned a threadsList which you need.

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

Comments

1

It's a bit hard to be sure without seeing what kind of classes you use, but assuming you use data classes, it can be done similarly to this:

val cleanThreadList = threadList.map { thread ->
    thread.copy(
        messages = thread.messages.filter {
            it.text == "@"
        }
    )
}

Edit (solution if your classes are mutable)

If your classes are mutable then it's similar but a bit different:

threadList.forEach { thread ->
    thread.removeIf { message ->
      message.text != "@"
    }
}

Comments

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.