Search code examples
kotlindata-class

how print the top sport by distance excluding eBikes in kotlin?


I want to print top sport by distance excluding eBikes in kotlin how can I achieve that

below my Kotlin classes

enum class Sport { HIKE, RUN, TOURING_BICYCLE, E_TOURING_BICYCLE }

data class Summary(val sport: Sport, val distance: Int)

fun main() {
    val sportStats = listOf(Summary(Sport.HIKE, 92),
            Summary(Sport.RUN, 77),
                Summary(Sport.TOURING_BICYCLE, 322),
                Summary(Sport.E_TOURING_BICYCLE, 656))
    
   
}

Solution

  • Here you go:

    sportStats
        .filterNot { it.sport == Sport.E_TOURING_BICYCLE }
        .maxBy { it.distance }
        ?.let { (sport, distance) -> 
            println("$sport is the top with distance $distance") 
        }
    

    Result:

    TOURING_BICYCLE is the top with distance 322