Scala地图密钥由2个逗号分隔组组成。如何在集合中提取第一个键?

发布于 2025-02-09 07:20:08 字数 321 浏览 0 评论 0原文

我有一个看起来像这样的scala地图集合:

var collection = Map((A,B) -> 1)

键是(a,b),值为1。

我的问题:如果我使用collection.head._1,结果为(a ,b)正确。但是我想仅提取一个没有b的无需提取,因为我需要将A与其他变量进行比较。因此,最终结果应该存储在不同的变量中。

我尝试使用collection.head._1(0)导致错误

任何不接受参数

I have a Scala map collection that looks something like this:

var collection = Map((A,B) -> 1)

The key is (A,B) and the value is 1.

My question: If I use collection.head._1, the result is (A,B) which is correct. But I want to extract A only, without B, as I need to compare A with some other variable. So the final result should be A stored in a different variable.

I tried to use collection.head._1(0) which results in error

Any does not take parameters

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

感性 2025-02-16 07:20:08

您可以尝试:

val collection = Map(("A","B") -> 1)
collection.map{ case ((a, b),v) => a -> v}

You can try:

val collection = Map(("A","B") -> 1)
collection.map{ case ((a, b),v) => a -> v}
递刀给你 2025-02-16 07:20:08

您可以使用将所有键作为set [(String,String)],然后map 它进入每个元素的第一个元素:

  val coll: Map[(String, String), Int] =
    Map(
      ("one", "elephant") -> 1,
      ("two", "elephants") -> 2,
      ("three", "elephants") -> 3
    )

  /*
  val myKeys = coll.keySet.map { case (x, _) => x }
  // equivalent to:
  val myKeys = coll.keySet.map(tup => tup._1)
  // equivalent to: */
  val myKeys = coll.keySet.map(_._1)  // Set(one, two, three)

You can use keySet to get all the keys as a Set[(String, String)] and then map it into the first element of each:

  val coll: Map[(String, String), Int] =
    Map(
      ("one", "elephant") -> 1,
      ("two", "elephants") -> 2,
      ("three", "elephants") -> 3
    )

  /*
  val myKeys = coll.keySet.map { case (x, _) => x }
  // equivalent to:
  val myKeys = coll.keySet.map(tup => tup._1)
  // equivalent to: */
  val myKeys = coll.keySet.map(_._1)  // Set(one, two, three)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文