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?
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 .
You can use sort() method to sort a Mutable List in-place, and sortDescending() for descending order.
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
try with sortBy method,
val result = tokens.sortBy { it.position }
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 Token
s by the position
, for example:
tokens.sortedBy { it.position.first }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With