You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scala技术问题:匹配字符串查找对应价格并生成指定格式结果

Scala: 匹配列表项并生成指定格式输出

你已经完成了前期的拆分工作,接下来咱们一步步实现匹配逻辑并生成目标输出:

步骤1:将拆分后的列表转换为案例类实例

首先把listSplit转换成Fruit案例类的列表,这样后续的属性匹配会更直观:

val fruitList = listSplit.map(arr => Fruit(arr(0), arr(1), arr(2).toInt))

这里要注意把价格字符串转成Int类型,确保和案例类的定义一致。

步骤2:提取目标匹配的水果名和月份

从拆分后的splitString里取出要匹配的两个字段:

val (targetName, targetMonth) = (splitString(0), splitString(1))

步骤3:找到匹配的列表项

使用find方法在fruitList中筛选出符合条件的项,它会返回Option[Fruit](避免找不到匹配项时出现空指针问题):

val matchedFruit = fruitList.find(f => f.name == targetName && f.month == targetMonth)

步骤4:生成指定格式的输出

通过模式匹配处理Option结果,生成要求的下划线分隔格式:

val output = matchedFruit match {
  case Some(fruit) => s"${fruit.name}_${fruit.month}_${fruit.price}"
  case None => "No matching entry found" // 可以根据需求自定义未找到时的提示
}

完整代码示例

把所有步骤整合起来:

case class Fruit(name: String, month: String, price: Int)

val listin = List("Apple,January,10", "Banana,August,15", "Strawberry,June,20")
val inputstring = "Banana,August"

val splitString = inputstring.split(",")
val listSplit = listin.map(_.split(","))

val fruitList = listSplit.map(arr => Fruit(arr(0), arr(1), arr(2).toInt))
val (targetName, targetMonth) = (splitString(0), splitString(1))
val matchedFruit = fruitList.find(f => f.name == targetName && f.month == targetMonth)

val output = matchedFruit match {
  case Some(fruit) => s"${fruit.name}_${fruit.month}_${fruit.price}"
  case None => "No matching entry found"
}

// 输出结果:Banana_August_15
println(output)

额外提示

如果你的输入可能存在格式不规范的情况(比如拆分后数组长度不足、价格无法转成数字),可以添加一些异常处理逻辑,比如用Try来包裹转换过程,避免程序崩溃。

内容的提问来源于stack exchange,提问作者scalacode

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:40:03