【问题标题】:Iterating over list with lambda forEach Kotlin使用 lambda forEach Kotlin 遍历列表
【发布时间】:2019-08-03 13:52:16
【问题描述】:

我有一个包含 30 个随机数的列表,它们对应于 8 种颜色中的一种,我需要遍历 8 种颜色(或 30 个数字)并找出每种颜色出现的次数。我需要使用 lambdas 和函数式编程来做到这一点,所以没有传统的 for 循环。

val iterator = colours.toList().iterator()

iterator.forEach{

    println("$it count: " + (numbers
            .map{a -> colours[a]}
            .count{it == ("$it")}))
}

目前的问题是我的计数输出仅为 50,而不是颜色出现的具体次数。

如果我这样做:

println("Red count:" +    (numbers
        .map{a -> colours[a]}
        .count{it ==  ("red")}))

它输出正确的数字,但不是循环。

它的输出:

green count: 50 

red count: 50

它应该输出什么(例如)

green count:9

red count:3

提前致谢

【问题讨论】:

    标签: android lambda kotlin


    【解决方案1】:

    在你的 forEach 循环中添加一个命名参数。隐含的名称“it”被 count 函数掩盖了。

    val iterator = colours.toList().iterator()
    
    iterator.forEach { colour ->
    
        println("$colour count: " + (numbers
            .map{a -> colours[a]}
            .count{it == ("$colour")}))
    }
    

    【讨论】:

      【解决方案2】:

      您实际上并不需要在这里进行嵌套迭代。目前您在 O(n^2) 操作,因为您必须为每个元素遍历列表一次。由于您知道您正在使用少量潜在值,因此您可以改为按值对它们进行分组,然后将值映射到结果列表的大小,即

      val colourNames = listOf("red", "green", "blue", "yellow", "orange", "indigo", "violet", "black")
      
      // Generates 30 random numbers between 0 and 8 (exclusive)
      val randomColours = (0 until 30).map { (0 until colourNames.size).random() }
      
      val result = randomColours
        .groupBy { color -> colourNames[color] } // outputs a Map<String, List<Int>>
        .mapValues { (color, colorCountList) -> colorCountList.size } // Map<String, Int>
      
      println(result) // {yellow=4, orange=4, red=5, indigo=3, blue=8, green=2, violet=2, black=2}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-25
        • 2011-01-21
        • 1970-01-01
        相关资源
        最近更新 更多