【问题标题】:Getting intersection of a keys of a map获取地图键的交集
【发布时间】:2014-06-17 13:47:25
【问题描述】:

这是我的地图

Map<String,Set<Integer>> transactions = new HashMap<String,Set<Integer>>();

这是字符串的集合

Set<String> check_set

现在的问题是如何制作这个方法

Set<Integer> getIntersection(Map<String,Set<Integer>> transactions, Set<String> check_set)

这将返回与 check_set 中的键对应的所有整数 Set 的交集。

如果地图是

tea=[1,3,5,7,9], 
milk=[2,3,6,7,9], 
sugar=[1,4,6,8,9]... 

如果 check_set 是{"tea","milk"},那么该方法应该返回存在于茶和牛奶中的值,即{3,7,9}。或者如果它有{"milk","sugar"},那么它应该返回{6,9}。如果它具有所有三个{"sugar","milk",tea"},那么它应该返回{3,9}

我知道我需要使用retainAll 函数来获取交集。但是如何制定一个逻辑来检查 map 中的所有整数集并得到它们的交集。

【问题讨论】:

  • 到目前为止你做了什么?
  • 我很困惑如何从这个问题开始。我曾想过对 Set of strings 使用迭代器,然后签入 map,但它不正确。
  • Sets.SetView() 将给出与在 retainAll() 中的临时集合中使用相同的交集。但我 check_set 可以有两个以上的元素。

标签: java algorithm collections map


【解决方案1】:

编辑:必须使用地图中第一组的副本(感谢 Bohemian)

在伪代码中,你可以有

Init result set to null to know it is still not initialized

Loop for each key in check_set
    if result is null then result = map{key} // take first set
    else result = intersection(result, map{key}) // and keep on intersecting

在java中给出

Set<Integer> result = null;
for (String key: check_set) {
    if (result == null) {
        result = new HashSet<Integer>(map.get(key));
    }
    else {
        result.retainAll(map.get(key));
    }
}

【讨论】:

  • 很好,除了我会创建一个新的 Set 而不是使用 Map 的值,因为 a) Map 的值可能是一个不可修改的 set,b) 你会改变 Map - 一个意想不到和不想要的一面效果。
  • 是的!这个解决方案解决了我的问题。这个对我有用。谢谢..:)
【解决方案2】:
private static Set<Integer> getIntersection(Map<String, Set<Integer>> transactions, Set<String> checkSet) {
    Iterator<String> iterator = checkSet.iterator();
    // create a copy of the original set
    Set<Integer> result = new HashSet<>(transactions.get(iterator.next()));
    while (iterator.hasNext()) {
        result.retainAll(transactions.get(iterator.next()));
    }
    return result;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 2013-04-18
    • 2011-02-16
    • 1970-01-01
    • 2022-08-16
    相关资源
    最近更新 更多