Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: how to use Google's HashBiMap?

Tags:

java

guava

Keys are a file and a word. The file gives all words inside the file. The word gives all files having the word. I am unsure of the domain and co-domain parts. I want K to be of the type <String> and V to be of type <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.

like image 291
hhh Avatar asked Nov 27 '22 12:11

hhh


2 Answers

change it to

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

But still it looks very strange. I think you should use another collection. From BiMap documentation (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.

I don't know the problem you want to solve but after looking at your code I can suggest to consider using Multimaps. From its docs:

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.

For example, you can do something like this:

Multimap<String, FileObject> wordToFiles = HashMultimap.create();
wordToFiles.put("first", somefile);
wordToFiles.put("first", anotherfile);
for (FileObject file : wordToFiles.get("first"){
   doSomethingWithFile (file);
}
like image 157
Roman Avatar answered Nov 30 '22 02:11

Roman


Add this dependency to your 'build.gradle'

compile 'com.google.guava:guava:19.0'

import BiMap and HashBiMap

import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;

Create a bimap

BiMap<String, String> myBiMap = HashBiMap.create();

Put some values

myBiMap.put("key", "value");

Get mapping value by key,

myBiMap.get("key");

Get mapping by value,

myBiMap.inverse().get("value");
like image 27
Sibin John Mattappallil Avatar answered Nov 30 '22 00:11

Sibin John Mattappallil