Java:如何使用谷歌的HashBiMap?

标签 java guava

键是一个文件和一个词。该文件给出了文件中的所有单词。这个词给出了所有有这个词的文件。我不确定域和共同域部分。我希望 K 属于 <String> 类型V 的类型为 <HashSet<FileObject>> .

    public HashBiMap<K<String>,V<HashSet<FileObject>>> wordToFiles 
            = new HashBiMap<K<String>,V<HashSet<FileObject>>>();

    public HashBiMap<K<String>,V<HashSet<FileObject>>> fileToWords 
            = new HashBiMap<K<String>,V<HashSet<FileObject>>>();

Google's HashBiMap.

最佳答案

改成

public HashBiMap<String,HashSet<FileObject>> wordToFiles = HashBiMap.create ();

但是看起来还是很奇怪。我认为你应该使用另一个集合。来自 BiMap 文档(HashBiMap impelements BiMap):

A bimap (or "bidirectional map") is a map that preserves the uniqueness of its values as well as that of its keys. This constraint enables bimaps to support an "inverse view", which is another bimap containing the same entries as this bimap but with reversed keys and values.

我不知道您要解决的问题,但在查看您的代码后,我可以建议考虑使用 Multimaps。从它的文档:

A collection similar to a Map, but which may associate multiple values with a single key. If you call put(K, V) twice, with the same key but different values, the multimap contains mappings from the key to both values.

例如,你可以这样做:

Multimap<String, FileObject> wordToFiles = HashMultimap.create();
wordToFiles.put("first", somefile);
wordToFiles.put("first", anotherfile);
for (FileObject file : wordToFiles.get("first"){
   doSomethingWithFile (file);
}

关于Java:如何使用谷歌的HashBiMap?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2574685/

相关文章:

java - 需要有关 Java 回文递归方法的帮助

java - Junit5的TestReporter线程安全吗?

java - Apache Camel onException 和 deadLetterChannel 问题

java - Luke - 当前位置没有有效的目录

java - java中的默认构造函数是如何被调用的?

java - SimpleTimeLimiter 超时 - 关闭应用程序需要很长时间

java - Guava:copyOf() 方法的 ImmutableList 魔法

java - 在 spring xml 配置中定义 guava HashBasedTable/Table

java - 为什么我需要在Java Guava中实现Apply功能?

java - directExecutor的优点