Can someone help me with this? The program should remove the duplicates and prin
ID: 653230 • Letter: C
Question
Can someone help me with this? The program should remove the duplicates and print out a list of how many members live in each state that has any members in it.
METHOD: First you need to read in the mailing list. Since you don't know how many addresses to expect, you'll want to use an ArrayList to store them. You'll need to read until the end of the file. This assignment can be done just using Strings, but I'd suggest creating a simple class to hold the addresses. Say, something like:
So, your list would be of type ArrayList<Address>. When reading the addresses, the city name might be more than one word (like "New York"), but the state abbreviation will always be the last word on the third line.
The easiest way to remove duplicates is to sort the list of addresses and then loop through and remove any address that is the same as the one before it.
To sort the list of addresses, you might use the method Collections.sort(). This method takes two parameters: the list to be sorted and an object of type Comparator. Like the ArrayList, the Comparator specifies what it is comparing, so if you're using the Address class above, it would be Comparator<Address>. Comparator is an interface which requires one method:
Here "T" represents the type of object being compared. Using the class above, it would be
Your compare() method can be very simple. For instance, just concatenating the Strings for the 4 fields and using String.compareTo() would be fine. If you wanted to be a bit fancier, your compare() method could first compare state, then city, etc. so that all of the addresses with the same states would be sorted together, then within those groups same cities, etc. This might simplify the last step of counting the number of members in each state.
Once the duplicates are removed, you should count how many members are in each state. There are various ways this could be done. One approach would be to create a list of just the state abbreviations from each address on the list. Then sort the list of abbreviations and then loop through that list counting how many of the first abbreviation you have (they'll all be together at the beginning of the list) and print that. Then, count the next abbreviation, etc. The program output should list state abbreviations in alphabetical order with the corresponding counts, something like: