Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - Sort MutableList based on Object Property

I have this Token Object:

class Token(type: TokenType, value: String, position: IntRange = 0..0)

I declare a MutableList:

val tokens: MutableList<Token> = mutableListOf()

// Mutable List filled

Now I want to sort my list based on the first value of the position IntRange. I tried doing this:

tokens
          .sortedBy { it.position.first }

However, I have no access to the object after using the it keyword, so position is highlighted red.

Any suggestions?

like image 640
OhMad Avatar asked Jul 16 '17 15:07

OhMad


People also ask

How do I sort custom objects in Kotlin?

Example: Sort ArrayList of Custom Objects By Property For sorting the list with the property, we use list 's sortedWith() method. The sortedWith() method takes a comparator compareBy that compares customProperty of each object and sorts it. The sorted list is then stored in the variable sortedList .

How do you sort a mutable list?

You can use sort() method to sort a Mutable List in-place, and sortDescending() for descending order.


3 Answers

Another observation is that sortedBy returns a sorted copy of the list. If you want to sort your mutable list in place, you should use sortBy function:

tokens.sortBy { it.position.first } 
// tokens is sorted now
like image 103
Ilya Avatar answered Sep 23 '22 01:09

Ilya


try with sortBy method,

val result = tokens.sortBy { it.position } 
like image 42
Codemaker Avatar answered Sep 22 '22 01:09

Codemaker


The position is a parameter rather than a property, to make it to a property on the primary constructor by val/var keyword, for example:

//makes the parameter to a property by `val` keyword---v
class Token(val type: TokenType,  val value: String,  val position:IntRange = 0..0)

THEN you can sort your Tokens by the position, for example:

tokens.sortedBy { it.position.first }
like image 22
holi-java Avatar answered Sep 21 '22 01:09

holi-java