for example, the code are like this, it is a little complicated, how can i use google's guava lib in this context and clean my code?
@Test
public void testMap2() {
Map<String, Map<String, String>> map = new HashMap<String, Map<String, String>>();
addToMap(map, "cib", "1004", "2");
addToMap(map, "cib", "1005", "3");
addToMap(map, "cib", "1006", "1");
addToMap(map, "cib", "1007", "5");
addToMap(map, "icbc", "1004", "2");
addToMap(map, "icbc", "1005", "3");
addToMap(map, "icbc", "1006", "1");
addToMap(map, "icbc", "1007", "5");
System.out.println(map);
}
private void addToMap(Map<String, Map<String, String>> map, String key, String name, String value) {
if(map.containsKey(key)) {
map.get(key).put(name, value);
} else {
Map<String, String> map1 = new HashMap<String, String>();
map1.put(name, value);
map.put(key, map1);
}
}
Yes, it's called Table
:
A collection that associates an ordered pair of keys, called a row key and a column key, with a single value. A table may be sparse, with only a small fraction of row key / column key pairs possessing a corresponding value.
The mappings corresponding to a given row key may be viewed as a Map whose keys are the columns. The reverse is also available, associating a column with a row key / value map. Note that, in some implementations, data access by column key may have fewer supported operations or worse performance than data access by row key.
There are few implementations:
ArrayTable
(backed by two-dimentional array, see the documentation), ForwardingTable
(implements decorator pattern), HashBasedTable
(~ HashMap<R, HashMap<C, V>
), ImmutableTable
(immutable and null-hostile), TreeBasedTable
(~ TreeMap<R, TreeMap<C, V>
)Also see the Wiki explaining Guava new collection types, specifically code example:
Table<Vertex, Vertex, Double> weightedGraph = HashBasedTable.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
which demonstrates clean way to achieve what you want.