gpt4 book ai didi

java - Scala - 如何将集合格式化为字符串?

转载 作者:行者123 更新时间:2023-11-29 04:06:42 26 4
gpt4 key购买 nike

我正在尝试将 Metrics 数据解析为格式化的字符串,以便有一个标题,下面的每条记录都从一个新行开始。最初我想获得类似于这样的表格格式的东西:

Id | Name  | Rate | Value
1L | Name1 | 1 | value_1
2L | Name2 | 2 | value_2
3L | Name3 | 3 | value_3

但我当前的实现导致以下错误:

java.util.MissingFormatArgumentException: Format specifier '%-70s'

我应该在我的代码中更改什么以使其格式正确?

import spark.implicits._
import org.apache.spark.sql.types._
import org.apache.spark.sql.functions._

case class BaseMetric(val id: Long,
val name: String,
val rate: String,
val value: String,
val count: Long,
val isValid: Boolean
) {

def makeCustomMetric: String = Seq(id, name, rate, value).mkString("\t")

}

val metric1 = new BaseMetric(1L, "Name1", "1", "value_1", 10L, true)
val metric2 = new BaseMetric(2L, "Name2", "2", "value_2", 20L, false)
val metric3 = new BaseMetric(3L, "Name3", "3", "value_3", 30L, true)

val metrics = Seq(metric1, metric1, metric1)



def formatMetrics(metrics: Seq[BaseMetric]): String = {
val pattern = "%-50s | %-70s | %-55s | %-65s | %f"

val formattedMetrics: String = pattern.format(metrics.map(_.makeCustomMetric))
.mkString("Id | Name | Rate | Value\n", "\n", "\nId | Name | Rate | Value")
formattedMetrics

}

val metricsString = formatMetrics(metrics)

最佳答案

特定错误是由于您将 Seq[String] 传递给需要 Any* 的格式。您只传递一个参数而不是五个。该错误表明它没有为您的第二个格式字符串找到参数。

您想将模式应用于每个指标,而不是模式上的所有指标。格式字符串中的填充对于您想要实现的目标来说太大了。

    val pattern = "%-2s | %-5s | %-4s | %-6s"
metrics.map(m => pattern.format(m.makeCustomMetric: _*))
.mkString("Id | Name | Rate | Value\n", "\n", "\nId | Name | Rate | Value")

_* 告诉编译器您要将列表作为可变长度参数传递。makeCustomMetric 应该只返回列表,而不是字符串。

def makeCustomMetric: String = Seq(id, name, rate, value)

关于java - Scala - 如何将集合格式化为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58172000/

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