wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes how to combine the objects in arraylist based on the object's field Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "how to combine the objects in arraylist based on the object Watch "how to combine the objects in arraylist based on the object New topic
Author

how to combine the objects in arraylist based on the object's field

sheng zhong
Greenhorn

Joined: Nov 23, 2006
Posts: 20
For example, arraylist1 of arraylist2:

[[195.03, 500, MYC], [195.03, 200, MYC], [195.01, 200, MYC], [194.98, 400, MYC], [194.95, 600, NYC]]

I want to combine the first 2 arraylists since they have the same field one(195.03) and same field 3(MYC), and add the second field together(500+200). After combination the output is:

[[195.03, 700, MYC], [195.01, 200, MYC], [194.98, 400, MYC], [194.95, 600, NYC]]

Thanks!!!

[ May 01, 2008: Message edited by: sheng zhong ]
[ May 01, 2008: Message edited by: sheng zhong ]
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38513
    
  23
Awkward.
I think you actually have a List of 4 objects, and you ought to get your elements into 4 objects. A List of Lists looks awkward to handle.

Then try sorting the List with Comparators for the 1st and last elements and iterate through the List with a for loop and combine pairs as appropriate.

It is likely there will be other ways to do it.
Anybody else got a better idea?
 
jQuery in Action, 2nd edition
 
subject: how to combine the objects in arraylist based on the object's field