Repository navigation
Expand file tree
/
Copy pathMultiMap.java
More file actions
49 lines (36 loc) · 1.44 KB
/
Copy pathMultiMap.java
File metadata and controls
49 lines (36 loc) · 1.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package examples;
import org.mapdb.BTreeKeySerializer;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import org.mapdb.Fun;
import java.util.NavigableSet;
/**
* Shows howto implement MultiMap (Map with more then one values for a singe key) correctly.
* To do 1:N mapping most people would use Map[String, List[Long]], however MapDB
* requires nodes to be immutable, so this is wrong.
*/
public class MultiMap {
public static void main(String[] args) {
DB db = DBMaker.newMemoryDB().make();
// this is wrong, do not do it !!!
// Map<String,List<Long>> map
//correct way is to use composite set, where 'map key' is primary key and 'map value' is secondary value
NavigableSet<Fun.Tuple2<String,Long>> multiMap = db.getTreeSet("test");
//optionally you can use set with Delta Encoding. This may save lot of space
multiMap = db.createTreeSet("test2")
.serializer(BTreeKeySerializer.TUPLE2)
.make();
multiMap.add(Fun.t2("aa",1L));
multiMap.add(Fun.t2("aa",2L));
multiMap.add(Fun.t2("aa",3L));
multiMap.add(Fun.t2("bb",1L));
//find all values for a key
for(Long l: Fun.filter(multiMap, "aa")){
System.out.println("value for key 'aa': "+l);
}
//check if pair exists
boolean found = multiMap.contains(Fun.t2("bb",1L));
System.out.println("Found: " + found);
db.close();
}
}