Skip to content
Advertisement

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

Advertisement

Answer

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.

2 People found this is helpful
Advertisement