I have two identical array lists in java each having a string value and an integer count. Now I have to merge these array lists into a single one, in which if the value is present, i will just increment the count, if the value is not present, i will just add the value and the count as such.
The question is, is there anyway I can do it graciously other than iterating in a for loop and if checking every value?
-
1could you give some example input/output pairs? your question is a little vague, and that could clear it up a bitmfsiega– mfsiega2012年04月12日 05:44:56 +00:00Commented Apr 12, 2012 at 5:44
-
Use Collection.addAll method.KV Prajapati– KV Prajapati2012年04月12日 05:45:47 +00:00Commented Apr 12, 2012 at 5:45
-
A map can be useful in task like this.Rangi Lin– Rangi Lin2012年04月12日 05:45:51 +00:00Commented Apr 12, 2012 at 5:45
-
@mfrankli Editing my question right now with an example.Greenhorn– Greenhorn2012年04月12日 05:46:44 +00:00Commented Apr 12, 2012 at 5:46
-
@RangiLin the problem is i get the arraylist from another system over which I don't have control :(Greenhorn– Greenhorn2012年04月12日 05:47:15 +00:00Commented Apr 12, 2012 at 5:47
2 Answers 2
You can't, there's too much custom logic. Iterate, check and add - that's the best approach, and will be more readable.
Technically, you can use a Multiset from guava, but there the count is taken care of by the collection itself, rather than you, so it might require some more work.
Comments
The question is, is there anyway I can do it graciously other than iterating in a for loop and if checking every value?
Short answer is no.
You would be better of using HashMap as a container, at least the merging operation would perform faster. You need a loop in any case. (since there is no addAll / putAll wich could update your counts).