Kotlin:如何在进行流操作时使用Intermediate集合。

huangapple go评论87阅读模式
英文:

kotlin: how to use the Intermediate collection when do stream operations

问题

x代表coordinates的map结果。我想在'all'步骤中使用它,如何做到这一点?

英文:

for example

val coordinates: Array<IntArray> = [[1, 2], [1, 3], [1, 4]]

coordinates
   .map {it[0]} 
   .all {it == x[0]}   


x means the map result of coordinates. I want use it in the 'all' step, how to do that?

答案1

得分: 1

你可以只写这个

coordinates
.map { it[0] }
.all { it == coordinates[0][0] }


或者如果你不想直接再次引用坐标,也许插入一个 `let` 像这样

coordinates
.map { it[0] }
.let { x -> x.all { it == x[0] } }


虽然对于你的特定用例,我可能只会这样做

coordinates
.all { it[0] == coordinates[0][0] }

英文:

You could just write this

coordinates
   .map {it[0]} 
   .all {it == coordinates[0][0]} 

Or if you don't want to directly refer to coordinates again, maybe insert a let like

coordinates
    .map { it[0] }
    .let { x -> x.all { it == x[0] } }

Although for your specific use case I probably would just do

coordinates
    .all { it[0] == coordinates[0][0] }

答案2

得分: 1

如果我理解正确,你可以简单地声明一个名为 xval 变量:

val x = coordinates.map { it[0] }
val result = x.all { it == x[0] }

或者,如果你想在一个表达式中完成,你可以使用作用域函数 runlet

val result = coordinates.map { it[0] }.run {
    all { it == this[0] }
}

或者:

val result = coordinates.map { it[0] }.let { x ->
    x.all { it == x[0] }
}

不过,如果你只想检查整个列表是否具有完全相同的唯一值,我认为以下方式更可读:

val result = coordinates.map { it[0] }.distinct().size == 1

上述方法不像 all 那样进行短路处理。要进行短路处理,需要使用 Sequence

val result = coordinates
    .asSequence()
    .map { it[0] }
    .distinct().take(2).count() == 1
英文:

If I understand correctly, you can just declare a val called x:

val x = coordinates.map { it[0] }
val result = x.all { it == x[0] }

Or if you want to do it in one expression, you can use the scope function run or let:

val result = coordinates.map { it[0] }.run {
    all { it == this[0] }
}

or:

val result = coordinates.map { it[0] }.let { x ->
    x.all { it == x[0] }
}

Though, if you just want to check if the whole list has exactly one unique value, I think this is more readable:

val result = coordinates.map { it[0] }.distinct().size == 1

The above doesn't short-circuit like all. A shortcircuiting version would need Sequence:

val result = coordinates
    .asSequence()
    .map { it[0] }
    .distinct().take(2).count() == 1

huangapple
  • 本文由 发表于 2023年2月8日 16:38:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/75383130.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定