I have a situation where i want to store data in an object with a key and its value. The key name is the same, but the value is changed. i tried to use hash Map but it also does not support this. it overwrites all values and gives me only the recent value in pair.
my question is: are there any classes or methods that can开发者_如何学Python help me sort out this problem?
What data structure to use
If the requirement is to store multiple values for a single key, then using a multimap would be a good option.
One implementation of such a multimap is the Multimap
from the Google Guava library.
The Multimap
interface in Guava has several implementations depending on the requirements for the multiplicity and ordering of the keys and values.
Choosing an implementation
A simple implementation is the HashMultimap
, where the values mapped by a key will not allow duplicates, and the ordering of the keys are not determinant.
The ArrayListMultimap
preserves the order of the values mapped to a key, in the order at which they were mapped to the key.
If you need to keep track of multiple values, you could possibly use a List
value in the Map. You could use the assumption that the last value in the List is the most recent value, if that meets your requirements.
Creating such a map would be done like this (though your key and value types don't have to be Strings, they could be whatever classes you're using):
Map<String, List<String>> map = new HashMap<String, List<String>>();
Then to get the latest value for a given key, you'd need to get the last element of the corresponding list:
List<String> list = map.get(key);
String value = null;
if (list != null) {
value = list.get(list.size() - 1);
}
To add a value to the Map, you'd need to add logic to create a new list if no value exists for a new key, otherwise add the new value to the end of the list:
if (map.get(key) == null) {
List<String> list = new ArrayList<String>();
list.add(value);
map.put(key, list);
}
else {
map.get(key).add(value);
}
Java's standard collections don't include a class for so-called "multimaps", but several other collection libraries offer this feature. Eg:
- MultiMap from Apache Commons
- Multimap from google-collections
精彩评论