Reputation:
I have three database tables defined below, column names mentioned in parenthesis:
Product (ProductID, Price, Last_Updated)
User (UserID, Name, Address, LocationID, Last_Updated)
Location (LocationID, Loc_Name, Last_Updated)
I want to use Java (JDK 1.5) to add all the column names of all the tables in one collection like a HashMap
.
My problem is when a duplicate key is entered, the previous value is over ridden.
I am adding them like:
Map<String, String> map = new HashMap<String, String>();
map.add("ProductID", "Save the Product ID");
// ...
map.add("Last_Updated", "Save Last_Updated of Product table");
// ...
map.add("LocationID", "Save the LocationID");
// ...
map.add("Last_Updated", "Save Last_Updated of User table.");
Now the key Last_Updated
is overridden with new value Save Last_Updated of User table.
But I want both the values.
Is there any way to implement this without using multiple HashMap
structures?
Upvotes: 0
Views: 6611
Reputation: 13807
If you want to add items with the same key, then this would be a possible solution
Map<String, List<String>> map = new HashMap<String, List<String>>();
when adding an element:
public void add(String key, String value) {
if(!map.containsKey(key)) {
map.put(key, new ArrayList<String>());
}
map.get(key).add(value);
}
And when you want to access an element, then by the maps get()
function you will get a List of strings, wich are the values for a key.
However, it would be best to use a Multimap implementation:
Multimap
- You can see the concrete implementations in the javadoc.
Multimap<String, String> map = ArrayListMultimap.create();
map.put("a", "Apple");
map.put("a", "Almonds");
Collection<String> valuesForA = map.get("a"); // List of ("Apple", "Almonds")
MultiMap
- Examples and concrete implementations in the javadoc
Upvotes: 2
Reputation: 6921
If you are limited to JDK 5, but allowed to use libraries, check out a publicly available MultiMaps: Guava has one, as does Commons Collections
Upvotes: 1
Reputation: 80176
Why not a denormalized table in an in-memory db like H2 or HSQL etc.
Upvotes: 0
Reputation: 8245
Add the table names as a prefix to your column names. Then you can separate "Product.Last_Updated", "User.Last_Updated" and "Location.Last_Updated".
Obviously you have to use a separator char that is not used in the names of your tables or columns; a '.' should do.
Upvotes: 1