4

Possible Duplicate:
How to implement a Map with multiple keys?

Imagine a table with columns K1, K2 and D. I may need to search data by keys K1 or K2 or both. Is there any 'standard' solution in Java for this apart from creating several maps keeping references?

Community
  • 1
  • 1
user1081596
  • 917
  • 1
  • 9
  • 16
  • "Imagine a table with columns K1, K2 and D." -- what do you mean by that? K1 - columns, K2 - rows and D is data in the intersection? Or K1 and K2 are columns and D is a row? In both cases it's not clear what should be returned "by keys K1 or K2 or both". – Sergey Grinev Jan 16 '12 at 14:49

4 Answers4

1

Consider using guava's Table.

Sample from the documentation

Table<Vertex, Vertex, Double> weightedGraph = HashTable.create();
weightedGraph.put(v1, v2, 4);
weightedGraph.put(v1, v3, 20);
weightedGraph.put(v2, v3, 5);

weightedGraph.row(v1); // returns a Map mapping v2 to 4, v3 to 20
weightedGraph.column(v3); // returns a Map mapping v1 to 20, v2 to 5
Mairbek Khadikov
  • 7,939
  • 3
  • 35
  • 51
0

If you wanted to search by only (k1, k2) tuples, I would suggest a MultiKeyMap or, more likely, a wrapper object going into a standard Map. But if you want to search by both, or one, or the other -- it sounds like an embedded SQL engine might be better.

EDIT: depending on your data size, whether you also need a (k1, k2, k3) lookup, how many structures like this you'll need (a SQL engine is relatively heavy), you might be better off with Mairbek Khadikov's answer of a Guava Table.

yshavit
  • 42,327
  • 7
  • 87
  • 124
0

If you are looking to search data by a range of keys then you can use navigable map.

Look at this code:

NavigableMap<String, String> orig = new TreeMap();
orig.put("1", "A");
orig.add("2", "B");
orig.add("3", "C");
orig.add("4", "D");
orig.add("5", "E"); 
//this submap will now contain "C", "C"
SortedMap submap = orig.subMap("2", "4");
anubhava
  • 761,203
  • 64
  • 569
  • 643
0

I would wrap the Map in an object and provide some method that would search for data using both keys. After that, you could simply intersect the 2 result sets and return them. Nice and simple :) .

Radu Murzea
  • 10,724
  • 10
  • 47
  • 69