Reputation: 4547
I am saving values into an Hashmap<String,Records>
Sample value 1,objRecord1
,2,objRecord2
,1,objRecord3
so on... I need to retrieve values of all records from hashmap whose string is 1
something like
(I am messing here itself)
arrayList myArraylist=Hashmap.get(1);
Upvotes: 1
Views: 1410
Reputation: 121998
arrayList myArraylist=Hashmap.get("1");
To satisfy that your Hashmap declaration must be
Map<String,List<Record>> myMap = new HashMap<>();
While adding add to list
Example for Adding in to map
:
if(myMap.containsKey("1")){
myMap.put("1", myMap.get("1").add(new Record()));//record obj
}else{
List<Record> list = new ArrayList<>();
list.add(record);
myMap.put("1", list));
}
Getting back
List<Record> list = myMap.get("1");
Upvotes: 0
Reputation: 830
If you want mulitple records per key then better to use Set of records for the values
Map<String, Set<Record>>
Upvotes: 0
Reputation: 3390
Better will be to use List as values in hashmap.
Something like: HashMap<String, List<Record>>
When you want to put record in map, you can do something like:
void insertRecord(String key, Record record){
List<Record> records = map.get(key);
if(records == null){
records = new ArrayList<Record>();
map.put(key, records);
}
records.add(record);
}
Upvotes: 0
Reputation: 272297
Do your multiple records per key need to be ordered ? If so, something like:
Map<String, List<Record>>
is suitable. Otherwise a Guava MultiMap would be suitable.
Upvotes: 0
Reputation: 19260
Use List or Set as Values, Then keep update that list or Set.
Hashmap<String, ArrayList<Records>>
Upvotes: 0
Reputation: 5612
Using a Multimap
would be easiest, in my opinion.
http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Multimap.html
That is if you're willing to add a dependency on google commons :)
NOTE: this is not the same as MultiMap
(notice the case difference) from apache commons.
Upvotes: 2