【问题标题】:Create a Map from the elements of the same set based on condition in Scala根据 Scala 中的条件从同一集合的元素创建 Map
【发布时间】:2020-10-10 07:16:58
【问题描述】:

我有一个如下形式的Hashset,它可能会变大:

var hs = HashSet(("fox", "name"),
    ("animal", "type"),
    ("gender", "type"),
    ("x", "test"),
    ("x", "nottest"),
    ("z", "test"),
    ("z", "nottest"))

使用以下形式从中获取地图的最佳方式是:

HashMap (("x", "test")-> ("x", "nottest"),("z", "test") ->("z", "nottest"))

即映射来自同一集合的元组,其中它们具有相同的第一个元素,第二个元素以“not”为前缀。

【问题讨论】:

    标签: scala dictionary functional-programming set scala-collections


    【解决方案1】:

    您可以创建所有可能的配对并过滤掉原始集合中不存在的配对:

    hs.map { case(k, v) => (k, v) -> (k, "not" + v) }
      .filter { case(pos, neg) => hs.contains(neg) }
      .toMap
    

    编辑:

    如果集合变得非常大,那么我们可以轻松更改排序 - 首先检查和过滤只有否定的对,然后映射:

    hs.filter { case(k, v) => hs((k, "not" + v)) }
      .map { case(k, v) => (k, v) -> (k, "not" + v) }
      .toMap
    

    【讨论】:

    • 集合可能会变大,有没有办法不创建所有对?另外,一个元组可能存在,但它的否定可能或反之亦然(我应该在问题中提到这一点,将对其进行编辑)
    • @Usr654789 简单,我们可以改变操作的顺序,看看我的编辑;>
    • @Usr654789 你跑了吗?它会产生您想要的确切结果。 (sth, notsth) (sth, sth) 是否存在并不重要。检查一种方式就足够了......
    • 刚刚做了,结果被正确过滤,但仍然是 HashSet 而不是 HashMap : HashSet(((z,test),(z,nottest)), ((x,test),(x ,nottest)))
    • @Usr654789 啊,忘了,直接打toMap就行了……
    猜你喜欢
    • 1970-01-01
    • 2021-06-02
    • 2021-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-30
    相关资源
    最近更新 更多