2019年5月5日日曜日

開発環境

Head First Kotlin: A Brain-Friendly Guide (Dawn Griffiths(著)、David Griffiths(著)、O'Reilly Media)のChapter 12(built-in higher-order functions - Power Up Your Code)、Sharpen your pencil(390)の解答を求めてみる。

コード

data class Grocery(
    val name: String, val category: String,
    val unit: String, val unitPrice: Double,
    val quantity: Int
)

val groceries = listOf(
    Grocery("Tomatoes", "Vegetable", "lb", 3.0, 3),
    Grocery("Mushrooms", "Vegetable", "lb", 4.0, 1),
    Grocery("Bagels", "Bakery", "Pack", 1.5, 2),
    Grocery("Olive oil", "Pantry", "Bottle", 6.0, 1),
    Grocery("Ice cream", "Frozen", "Pack", 3.0, 2)
)

fun main() {
    println("1.")
    println(
        groceries
            .filter { it.category == "Vegetable" }
            .sumByDouble { it.unitPrice * it.quantity }
    )
    println("2.")
    val names = groceries
        .filter { it.unitPrice * it.quantity < 5.0 }
        .map { it.name }
    names.forEach { println(it) }

    println("3.")
    groceries
        .groupBy { it.category }
        .forEach {
            println("${it.key}: ${it.value.sumByDouble { it.unitPrice * it.quantity }}")
        }

    println("4.")
    groceries
        .filterNot { it.unit == "Bottle" }
        .groupBy { it.unit }
        .forEach {
            println(it.key)
            it.value.forEach {
                println("\t${it.name}")
            }
        }
}

入出力結果

1.
13.0
2.
Mushrooms
Bagels
3.
Vegetable: 13.0
Bakery: 3.0
Pantry: 6.0
Frozen: 6.0
4.
lb
 Tomatoes
 Mushrooms
Pack
 Bagels
 Ice cream

Process finished with exit code 0

0 コメント:

コメントを投稿

関連コンテンツ