Collapse sorted().first/last() and reversed().first/last() chains

Proprietary

Replaces O(n log n) sorts whose only purpose is to read one element with the equivalent O(n) min/max/minBy/maxBy, and elides unnecessary reversed() copies before first/last.

org.openrewrite.kotlin.performance.CollapseSortAndReverse$KtRecipe
mod run . --recipe='org.openrewrite.kotlin.performance.CollapseSortAndReverse$KtRecipe'

Install it once from Recipe actions, then run it on every repository under the current directory. New to the Moderne CLI? Set it up.

Recipe list

It runs these recipes, in this order.

  1. Use min() instead of sorted().first()
  2. Use max() instead of sorted().last()
  3. Use max() instead of sortedDescending().first()
  4. Use min() instead of sortedDescending().last()
  5. Use minBy { selector } instead of sortedBy { selector }.first()
  6. Use maxBy { selector } instead of sortedBy { selector }.last()
  7. Use last() instead of reversed().first()
  8. Use first() instead of reversed().last()
  9. Use sortedByDescending { f } instead of sortedBy { f }.reversed()
  10. Use sortedDescending() instead of sorted().reversed()
  11. Use mapTo(mutableListOf(), f) instead of map(f).toMutableList()
  12. Use filterTo(mutableListOf(), p) instead of filter(p).toMutableList()
  13. Use filterNotTo(mutableListOf(), p) instead of filterNot(p).toMutableList()
  14. Use flatMapTo(mutableListOf(), f) instead of flatMap(f).toMutableList()