I'm having a hard time remove duplicate items from my ArrayList of custom objects.
Removing Duplicates
public static ArrayList<UnchainedRestaurant> removeDuplicates(ArrayList<UnchainedRestaurant> arraylist) {
//remove any duplicates
ArrayList<UnchainedRestaurant> noDuplicates = new ArrayList<>();
Set<UnchainedRestaurant> setItems = new LinkedHashSet<UnchainedRestaurant>(arraylist);
noDuplicates.addAll(setItems);
return noDuplicates;
}
Custom Object equals()
public boolean equals(Object o) {
UnchainedRestaurant r = (UnchainedRestaurant) o;
String name1 = this.getName();
String name2 = r.getName();
name1 = Util.normalizeVenueName(name1);
name2 = Util.normalizeVenueName(name2);
if(name1.equals(name2)) {
return true;
} else return false;
}
Output after removing duplicates
1. 786 Kebab & Curry
2. Marlow's Tavern
3. P.F. Chang's
4. Ted's Montana Grill
5. Which Wich? Superior Sandwiches
6. Niko Niko Sushi
7. Burger 21
8. Tin Lizzys Bar and Grille
9. Saigon Flavors
10. Firehouse Subs
11. Luigi's Pizza
12. Roya Mediterranean Restaurant and Tapas Bar
13. East Coast Wings & Grill
14. Provino's Italian Restaurant
15. Kani House
16. Chow Baby
17. Mimi's Cafe
18. Monterrey Mexican Restaurant
19. Panera Bread - Mall of Georgia
20. Umami Asian Cuisine
21. Parma Tavern
7. Burger 21 --------------------------------
23. Luigi's A Slice of Italy
4. Ted's Montana Grill --------------------------------
25. Tom + Chee - Buford
2. Marlow's Tavern --------------------------------
1. 786 Kebab & Curry
28. Sushi Niko Niko
13. East Coast Wings & Grill
3. P.F. Chang's --------------------------------
31. Turkish Kitchen
32. The Cheesecake Factory
17. Mimi's Cafe
34. Aha Sushi
15. Kani House
3. P.F. Chang's --------------------------------
37. Teavana
38. Williams-Sonoma
39. Great Wraps
40. Auntie Anne's Pretzels
1. 786 Kebab & Curry --------------------------------
42. Bruster's Real Ice Cream
43. Spencer Gifts
44. Pretzelmaker
45. Little Tokyo of Georgia Mall
46. Great American Cookies
Any tips as to why it's not actually removing duplicates? Or is it actually removing duplicates by replacing the duplicate with the original? Not sure what's going on here.
LinkedHashSet.Setdoes not do it for you. It uses equals and hashcode so that it can find whether the object is a duplicate or not (for hash set in particular).