Reputation: 3556
I have three object classes called Size1
, Size2
, Size3
All Size classes has different values (all Values are Strings):
I want to sort a List so that it wouldn't contain duplicate values.
Here it is what I tried:
private List<Size> getSortedSizes(List<Size> allSizes){
List<Size> sortedArray = new ArrayList<>();
for (int i = 0; i < allSizes.size(); i++){
Size size = allSizes.get(i);
if (sortedArray.size() == 0){
sortedArray.add(Size);
} else {
for (int a = 0; a < sortedArray.size(); a++) {
if (!sortedArray.get(a).getValue().equals(Size.getValue())) {
sortedArray.add(Size);
}
}
}
}
return sortedArray;
}
Upvotes: 1
Views: 83
Reputation: 1089
You could implement your method in the following way:
private Set<Size> getSortedSizes(List<Size> allSizes) {
Set<Size> sorted = new TreeSet<>(sortedArray);
return sorted;
}
But you have to implement two methods in your Size class, they are: hashCode() and int compareTo(Object o) from the Comparable interface
Upvotes: 1
Reputation: 191701
Add to a TreeSet, not an Arraylist
TreeSets are ordered and cannot contain duplicates
Upvotes: 3