Remove duplicates from a sorted ArrayList while keeping some elements from the duplicates
- by js82
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!!!