【问题标题】:Get a unique string from string split从字符串拆分中获取唯一的字符串
【发布时间】:2021-05-10 02:29:18
【问题描述】:

我想从输入中获得List[String]。请帮我找到一个优雅的方式。

期望的输出:

emp1,emp2

我的代码:

val ls = List("emp1.id1", "emp2.id2","emp2.id3","emp1.id4")

def myMethod(ls: List[String]): Unit = {
  ls.foreach(i => print(i.split('.').head))
}

(myMethod(ls)). //set operation to make it unique ??

【问题讨论】:

  • 这里的 unique 是什么意思?
  • 请详细说明您想要实现的目标?

标签: list scala


【解决方案1】:
def myMethod(ls: List[String]) =
  ls.map(_.takeWhile(_ != '.'))

myMethod(ls).distinct

【讨论】:

  • 这也有效。您是否看到任何差异或问题(拆分并针对 takeWhile) ls.map(_.split('.').head)
  • 我认为它更好地表达了逻辑,并且一碰到'。'就停止了。而不是检查整个字符串。
【解决方案2】:

如果您关心验证,可以考虑使用正则表达式:

val ls = List("emp1.id1", "emp2.id2","emp2.id3","emp1.id4","boom")
  
  def myMethod(ls: List[String]) = {
    val empIdRegex = "([\\w]+)\\.([\\w]+)".r
    val employees = ls collect { case empIdRegex(emp, _) => emp }
    employees.distinct
  }

println(myMethod(ls))

输出:

List(emp1, emp2)

【讨论】:

  • 完美。非常感谢 Zvi。
【解决方案3】:

从 Scala 2.13 开始,您可以使用 List.unfold 来执行此操作:

List.unfold(ls) {
  case Nil =>
    None
  case x :: xs =>
    Some(x.takeWhile(_ != '.'), xs)
}.distinct

请不要说您想要不同的值,因此您可以使用 Set.unfold 实现相同的目的:

Set.unfold(ls) {
  case Nil =>
    None
  case x :: xs =>
    Some(x.takeWhile(_ != '.'), xs)
}

代码在Scastie 运行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-18
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多