Say I have a class Foo(val a: String, val b: Int, val c: Date)
and I want to sort a list of Foo
s based on all three properties. How would I go about this?
相关问题
- How to refresh height of a Constrained View in Con
- Android Room Fetch data with dynamic table name
- Access Binding Adapters in multi module project
- How to make request-bound data globally available
- In Vertx I need to redirect all HTTP requests to t
相关文章
- How does compareTo work?
- SonarQube: How to suppress a warning in Kotlin cod
- What are the `^let` annotations in Android Studio
- Create Custom Dagger 2 Scope with Kotlin
- Android Studio 3.5 ERROR: Unable to resolve depend
- Kotlin inlined extension property
- Kotlin Koans with EduTools plugin: “Failed to laun
- “lateinit” or “by lazy” when defining global andro
Kotlin's stdlib offers a number of useful helper methods for this.
First, you can define a comparator using the
compareBy()
method and pass it to thesortedWith()
extension method to receive a sorted copy of the list:Second, you can let
Foo
implementComparable<Foo>
using thecompareValuesBy()
helper method:Then you can call the
sorted()
extension method without parameters to receive a sorted copy of the list:Sorting direction
If you need to sort ascending on some values and descending on other values, the stdlib also offers functions for that:
Performance considerations
The
vararg
version ofcompareValuesBy
is not inlined in the bytecode meaning anonymous classes will be generated for the lambdas. However, if the lambdas themselves don't capture state, singleton instances will be used instead of instantiating the lambdas everytime.As noted by Paul Woitaschek in the comments, comparing with multiple selectors will instantiate an array for the vararg call everytime. You can't optimize this by extracting the array as it will be copied on every call. What you can do, on the other hand, is extract the logic into a static comparator instance and reuse it: