I have a List of Objects like List
.I want to sort this list alphabetically using Object name field. Object contains 10 field and name field is o
if(listAxu.size() > 0){
Collections.sort(listAxu, new Comparator<Situacao>(){
@Override
public int compare(Situacao lhs, Situacao rhs) {
return lhs.getDescricao().compareTo(rhs.getDescricao());
}
});
}
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());
}
});
}
If your objects has some common ancestor [let it be T
] you should use List<T>
instead of List<Object>
, and implement a Comparator for this T, using the name field.
If you don't have a common ancestor, you can implement a Comperator, and use reflection to extract the name, Note that it is unsafe, unsuggested, and suffers from bad performance to use reflection, but it allows you to access a field name without knowing anything about the actual type of the object [besides the fact that it has a field with the relevant name]
In both cases, you should use Collections.sort() to sort.
I found another way to do the type.
if(listAxu.size() > 0){
Collections.sort(listAxu, Comparator.comparing(IdentityNamed::getDescricao));
}
something like
List<FancyObject> theList = … ;
Collections.sort (theList,
new Comparator<FancyObject> ()
{ int compare (final FancyObject a, final FancyObject d)
{ return (a.getName().compareTo(d.getName())); }});
Using Java 8 Comparator.comparing:
list.sort(Comparator.comparing(Campaign::getName));