kotlin
  • Kotlin
  • Variable
  • Function
  • First Class Citizen
  • High Order Function
  • Pure Function
  • Call by Value, Call by Name
  • Null Safe
  • Generic
  • Expression
    • if - else
    • when
    • try - catch
    • while
    • for
  • Class
    • abstract
    • constructor
    • Data Class
    • Default Value
    • enum
    • inheritance
    • interface
    • open
    • property
    • sealed
  • Kotlin Standard
    • let
    • with
    • apply
    • run
    • also
    • takeIf
    • takeUnless
    • use
    • repeat
  • Collections
    • Mutable
    • Immutable
    • Collections
    • Aggregate operations
      • any
      • all
      • count
      • fold
      • foldRight
      • fold vs foldRight
      • forEach
      • forEachIndexed
      • max
      • maxBy
      • min
      • minBy
      • none
      • reduce
      • reduceRight
      • sum
      • sumBy
    • Filtering operations
      • drop
      • dropLast
      • dropWhile
      • dropLastWhile
      • filter
      • filterNot
      • slice
      • take
      • takeLast
      • takeWhile
    • Mapping operations
      • map
      • mapIndexed
      • flatMap
      • groupBy
    • Elements operations
      • contains
      • elementAt
      • elementAtOrElse
      • elementAtOrNull
      • first
      • firstOrNull
      • indexOf
      • indexOfFirst
      • indexOfLast
      • last
      • lastIndexOf
      • lastOrNull
      • single
      • singleOrNull
    • Generation operations
      • partition
      • plus
      • minus
      • zip
      • unzip
    • Ordering operations
      • reversed
      • sorted
      • sortedBy
      • sortedDescending
      • sortedByDescending
Powered by GitBook
On this page
  1. Collections
  2. Aggregate operations

maxBy

실제 어떤값을 비교할 것인지에 대한 식을 파라미터로 전달해 최대값을 얻는다.

public inline fun <T, R : Comparable<R>> Iterable<T>.maxBy(selector: (T) -> R):T? {
    val iterator = iterator()
    if (!iterator.hasNext()) return null
    var maxElem = iterator.next()
    var maxValue = selector(maxElem)
    while (iterator.hasNext()) {
        val e = iterator.next()
        val v = selector(e)
        if (maxValue < v) {
            maxElem = e
            maxValue = v
        }
    }
    return maxElem
}


val list = listOf(Person("a", 10),
        Person("b", 30),
        Person("c", 15))
        
println(list.maxBy{ it.age })  //Person(name=b, age=30)

PreviousmaxNextmin

Last updated 6 years ago