How to sort a List<Object> alphabetically using Object name field
Solution 1:
From your code, it looks like your Comparator
is already parameterized with Campaign
. This will only work with List<Campaign>
. Also, the method you're looking for is compareTo
.
if (list.size() > 0) {
Collections.sort(list, new Comparator<Campaign>() {
@Override
public int compare(final Campaign object1, final Campaign object2) {
return object1.getName().compareTo(object2.getName());
}
});
}
Or if you are using Java 1.8
list
.stream()
.sorted((object1, object2) -> object1.getName().compareTo(object2.getName()));
One final comment -- there's no point in checking the list size. Sort will work on an empty list.
Solution 2:
The most correct way to sort alphabetically strings is to use Collator
, because of internationalization. Some languages have different order due to few extra characters etc.
Collator collator = Collator.getInstance(Locale.US);
if (!list.isEmpty()) {
Collections.sort(list, new Comparator<Campaign>() {
@Override
public int compare(Campaign c1, Campaign c2) {
//You should ensure that list doesn't contain null values!
return collator.compare(c1.getName(), c2.getName());
}
});
}
If you don't care about internationalization use string.compare(otherString)
.
if (!list.isEmpty()) {
Collections.sort(list, new Comparator<Campaign>() {
@Override
public int compare(Campaign c1, Campaign c2) {
//You should ensure that list doesn't contain null values!
return c1.getName().compare(c2.getName());
}
});
}
Solution 3:
Using Java 8 Comparator.comparing:
list.sort(Comparator.comparing(Campaign::getName));