1

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?

5
  • 1
    could you give some example input/output pairs? your question is a little vague, and that could clear it up a bit Commented Apr 12, 2012 at 5:44
  • Use Collection.addAll method. Commented Apr 12, 2012 at 5:45
  • A map can be useful in task like this. Commented Apr 12, 2012 at 5:45
  • @mfrankli Editing my question right now with an example. Commented Apr 12, 2012 at 5:46
  • @RangiLin the problem is i get the arraylist from another system over which I don't have control :( Commented Apr 12, 2012 at 5:47

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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).

Comments

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.