How to sort a List<Object> alphabetically using Object name field
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.
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());
}
});
}
Have a look at Collections.sort()
and the Comparator
interface.
String comparison can be done with object1.getName().compareTo(object2.getName())
or object2.getName().compareTo(object1.getName())
(depending on the sort direction you desire).
If you want the sort to be case agnostic, do object1.getName().toUpperCase().compareTo(object2.getName().toUpperCase())
.