'Sort a List of objects based in its Sublist method size
I'm trying to make my own "Facebook reaction bar" and I got into a problem, I need to sort a list of objects based in its sublist method size, let me explain!
I have a ReactionModel which has a property "usernames" which is a List of Strings of usernames of those users that used it.
I have a list of ReactionModel which represent the reactions, for example this:
val reactionsList: List<ReactionModel> = listOf(
ReactionModel(listOf("a","b","c")),
ReactionModel(listOf("z")),
ReactionModel(listOf("f","d"))
)
In this case the first one is the largest, after that the third one and finally the second one.
I need to sort the reactionList and got a decreasing of it based on the size of usernames property.
Input:
ReactionModel(listOf("a","b","c")),
ReactionModel(listOf("z")),
ReactionModel(listOf("f","d"))
Output:
ReactionModel(listOf("z")),
ReactionModel(listOf("f","d")),
ReactionModel(listOf("a","b","c"))
I tried using forEach's but without success. I found some question here but is comparing just two list. Hope to find any answer, thanks for your time!!
Edit: Is for Android, so the answer can be in Java or Kotlin
Solution 1:[1]
sortedBy can be used for this, I'm assuming the name of the string list in ReactionModel is stringList.
val sortedList = reactionsList.sortedBy {
it.stringList.size
}
sortedBy doesn't change the existing list, but returns the sorted list.
Solution 2:[2]
With Kotlin, you can do it using single line,
reactionsList.sortedByDescending { it.{getYourListHere}.size }
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Praveen |
| Solution 2 | DHAVAL A. |
