简体   繁体   English

根据 Scala 中的条件,从同一集合的元素创建 Map

[英]Create a Map from the elements of the same set based on condition in Scala

I have a Hashset of the following form, it might grow big:我有以下形式的Hashset ,它可能会变大:

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

What is the best way to have a Map from it with the following form:使用以下形式从中获得 Map 的最佳方法是什么:

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

ie Mapping the tuples from the same set where they have the same first element and the second element is prefixed with "not".即映射来自相同集合的元组,其中它们具有相同的第一个元素,而第二个元素以“not”为前缀。

You can create all possible pairs and filter out the ones, that are not present in the original set:您可以创建所有可能的配对并过滤掉原始集合中不存在的配对:

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

Edit:编辑:

If the set grows really large, then we can easily change the ordering - first check and filter only pairs with negations, then map:如果集合变得非常大,那么我们可以轻松地更改排序 - 首先检查和过滤只有否定的对,然后是 map:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM