This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
I have a scenario for which I am looking for the most efficient approach.
I have key value pairs coming to the system in form of a long string for e.g. K1,V1;K1,V2;K2,V3;K2V4;K3,V5
I need to display it in form of
Approach I am thinking:
1. create string tokens token 1 - K1,V1 token 2 - K1V2 etc, add them to a list KeyValuesRawList 2. create string tokens token 1 K1, token 2 K2 etc, add them to a list KeyList 4. create a map finalMap, lists valueList1,valueList2,valueList3 3. Iterate through KeyValuesRawList,
3.1 create tokens tempK and tempV
3.2 if (tempK = K1)
add tempV to valueList1
if(tempK = K2)
add tempV to valueList2
if(tempK = K3)
add tempV to valueList3
3.3 Add values from list KeyList as keys to finalMap
3.4 Add values from lists valueList1,valueList2,valueList3 as values to finalMap
Apache Commons has a solution to this called the MultiMap. If you can, see if you can just use that instead of re-inventing things.
Otherwise, the idea should be to use a Map that maps the String key to a list of values (Map<String, List<String>>). You would add values into the Map like this:
As for how to get from a String where the values are listed like: K1,KV1;K1,V2;etc... into the Map, there probably isn't a need to go through all those intermediary lists. Use String.split to break the string into KV pairs, then split the KV pair again and add the results to the map:
Please take this all as pseudocode, I did not compile, test, or review it to make sure it didn't have any glaring mistakes. The point is just that you can go directly from the full string (rawInput) and get to the map without creating lots of intermediary lists. You use the String.split to create an array of all Key:Value pairs, then you split each pair and add it to the Map immediately.
Also, in the future, when posting code (such as a small snippet as an example, but not, of course, a full solution), please UseCodeTags(⇐click) so it will be readable.
Joined: Apr 05, 2012
Thanks everyone for the suggestions. As suggested by you I am using HashMap with String as key and ArrayList<String> as value.
And to implement the multiMap concept, I am using Steve's implementation.
Thanks for making it that simple