java-如何在循环中找到Hashset中的值的交集?

我用 Java 编写了一个程序,它从数据库表中检索记录并将它们存储在哈希图中。


它们的键和值如下所示:


Key(represent words)      Values(represent filename)


w1                          file1

w2                          file1

w3                          file2

w4                          file1

w5                          file2

w6                          file1,file2

............

列表还在继续,但这只是它的外观的一个想法。如您所见,单词没有重复,它们是独一无二的。


鉴于我有这个哈希图信息,我需要找到键的交集和它的下一个键并返回交集的结果。这个想法看起来像这样:


w1∩w2= file1

w2∩w3= empty

w3∩w4= empty

........它会一直运行,直到完成 hashmap 中的最后一对键。


由于这对交集结果取决于哈希图中的键数,我猜我需要使用一些循环来保持它迭代以返回所有结果。


有没有一种方法可以获取每个后续键的交集,也有一种方法可以优化而不考虑哈希图的大小?


我很感激任何建议。


慕沐林林
浏览 156回答 2
2回答

当年话下

创建一个变量来保存所有这些交叉点。在您的循环中一次检索 2 个键。比较 2 个键的每个值,如果它们相同,则将该值添加到您的交叉点持有人。重复这些步骤,直到不再有对。这是代码。在你的 try/catch 下添加这个LinkedHashmap<String, Set<String>> intersectionMap = new LinkedHashmap<>();if (map.keySet() != null) {&nbsp; &nbsp; String[] keys = map.keySet().toArray(new String[map.keySet().size()]);&nbsp; &nbsp; for (int i = 0; i < keys.length - 1; i++) {&nbsp; &nbsp; &nbsp; &nbsp; String key1 = keys[i];&nbsp; &nbsp; &nbsp; &nbsp; String key2 = keys[i + 1];&nbsp; &nbsp; &nbsp; &nbsp; TreeSet<String> interSection = intersection(map.get(key1), map.get(key2));&nbsp; &nbsp; &nbsp; &nbsp; intersectionMap.put(key1 + "∩" + key2, interSection);&nbsp; &nbsp; }}添加此辅助方法。此方法将找到两个集合的交集。这将是解决您的问题的关键。public static TreeSet<String> intersection(TreeSet<String> setA, TreeSet<String> setB) {&nbsp; &nbsp; // An optimization to iterate over the smaller set&nbsp; &nbsp; if (setA.size() > setB.size()) {&nbsp; &nbsp; &nbsp; &nbsp; return intersection(setB, setA);&nbsp; &nbsp; }&nbsp; &nbsp; TreeSet<String> results = new TreeSet<>();&nbsp; &nbsp; for (String element : setA) {&nbsp; &nbsp; &nbsp; &nbsp; if (setB.contains(element)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; results.add(element);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return results;}

jeck猫

另一个带有集合操作的版本:Map<String>, Set<String>> intersections(Map<String, TreeSet<String>> map) {&nbsp; &nbsp; Map<String>, Set<String>> result = new TreeMap<>();&nbsp; &nbsp; List<String> words = new ArrayList<>(map.keySet());&nbsp; &nbsp; words.sort();&nbsp; &nbsp; for (int i = 0; i < words.size() - 1; ++i) {&nbsp; &nbsp; &nbsp; &nbsp; String wordI = words.get(i);&nbsp; &nbsp; &nbsp; &nbsp; Set<String> valueI = map.get(wordI);&nbsp; &nbsp; &nbsp; &nbsp; for (int j = i + 1, j < words.size(); ++j) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String wordJ = words.get(j);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Set<String> valueJ = map.get(wordJ);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String word = wordi + "∩" + words[j];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Set<String> value = new TreeSet<>(valueI);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; value.retainAll(valueJ);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result.put(word, value);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return result;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java