gpt4 book ai didi

Scala 过滤序列以与尊重和不尊重过滤条件的元素进行映射

转载 作者:行者123 更新时间:2023-12-02 19:12:02 25 4
gpt4 key购买 nike

我有一个字符串序列:

val results = Seq("", "one", "two", "three")

使用两个过滤器我得到:

val emptyStrings: Seq[String] = results.filter( s => s.isEmpty )
val notEmptyStrings: Seq[String] = results.filterNot( s => s.isEmpty )

是否可以通过一个过滤器获得 Map[Boolean, Seq[String]] :

  • key = isEmpty true/false
  • 值 = 空或非空字符串

最佳答案

$ scala
Welcome to Scala 2.13.0 (OpenJDK 64-Bit Server VM, Java 1.8.0_262).
Type in expressions for evaluation. Or try :help.

scala> val results = Seq("", "one", "two", "three")
results: Seq[String] = List("", one, two, three)

scala> results.groupBy(_.isEmpty)
res0: scala.collection.immutable.Map[Boolean,Seq[String]] = HashMap(false -> List(one, two, three), true -> List(""))

更好的选择是使用 partition 因为它返回一个包含 2 个值的元组而不是一个映射:

scala> results.partition(_.isEmpty)
res1: (Seq[String], Seq[String]) = (List(""),List(one, two, three))

或者更好地将结果与命名值进行模式匹配:

scala> val (emptyStrings, nonEmptyStrings) = results.partition(_.isEmpty)
emptyStrings: Seq[String] = List("")
nonEmptyStrings: Seq[String] = List(one, two, three)

关于Scala 过滤序列以与尊重和不尊重过滤条件的元素进行映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64152985/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com