2

I have multiple records received as string through a query. I want to store records having the same "long" key in a collection dynamically as I parse them in a loop. Like, insert key and value and if the key exists, it adds to the values and if not, a new key is created. What would be the most efficient way of doing this? I can do it using multiple arrays but I would prefer a cleaner way.

I cannot use a HashMap as I have to first store the records in an Array or ArrayList and then insert it which defeats the purpose as I have to group the lists by key first anyway. The no. of records will not more than 50 at a time.

E.g data:

for(i = 0; i < numRecords; i++ ) {  
    Data: 1 "A", 2 "B", 1 "C", 3 "D", 1 "E"   
}

I want to have a collection where inside the loop I can just add: 1 "A" and so on..

1 Answer 1

4

I think Map<Long,List<String>> may help you.

Map<Long,List<String>> map = new HashMap<>();
...
if(map.get(key)!=null){
  List<String> list = map.get(key);
  list.add(value);
}else{
  List<String> list = new ArrayList<>();
  list.add(value);
  map.put(key,list);
}
Sign up to request clarification or add additional context in comments.

5 Comments

Why do I get this error: '<>' operator is not allowed for source level below 1.7 for both the new HashMap and ArrayList declaration. I want to use only Java 1.6
then use new HashMap<Long,List<String>>() as empty <> are not supported for java 1.6
Yes this suits my purpose ver well. Thank you very much!
One more question, how efficient would be using this and then iterating again in the next segment to get the values for so few records? And can I have multiple values to one key? e.g. Long key has List<String> and List<int> as values?
Got it. Just created a class with values as members and gave the class object as List type. Thanks a lot for your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.