Okay at first I thought this would be pretty straightforward. But I can’t think of an efficient way to solve this. I figured a brute force way to solve this but that’s not very elegant. I have an ArrayList. Contacts is a VO class that has multiple members – name, regions, id. There are duplicates in ArrayList because different regions appear multiple times. The list is sorted by ID. Here is an example:
Entry 0 – Name: John Smith; Region: N; ID: 1
Entry 1 – Name: John Smith; Region: MW; ID: 1
Entry 2 – Name: John Smith; Region: S; ID: 1
Entry 3 – Name: Jane Doe; Region: NULL; ID: 2
Entry 4 – Name: Jack Black; Region: N; ID: 3
Entry 6 – Name: Jack Black; Region: MW; ID: 3
Entry 7 – Name: Joe Don; Region: NE; ID: 4
I want to transform the list to below by combining duplicate regions together for the same ID. Therefore, the final list should have only 4 distinct elements with the regions combined.
So the output should look like this:-
Entry 0 – Name: John Smith; Region: N,MW,S; ID: 1
Entry 1 – Name: Jane Doe; Region: NULL; ID: 2
Entry 2 – Name: Jack Black; Region: N,MW; ID: 3
Entry 3 – Name: Joe Don; Region: NE; ID: 4
What are your thoughts on the optimal way to solve this? I am not looking for actual code but ideas or tips to go about the best way to get it done.
Thanks for your time!!!
You can iterate them while dumping them (and merging duplicates) into a TreeMap. Then create a list from the sorted view of the TreeMap’s values.
In the sample code I’m assuming you have an Entry class with id, name and regions fields this last one being a List of Region instances. This could easily be changed to a Set, and Region to Strings or whatever you’re using. The sample copies the entries before inserting them into the map since they will be modified when merged to other entries.