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
Try this:
List< Object> myList = x.getName;
myList.sort(Comparator.comparing(Object::getName));
This is assuming a list of YourClass
instead of Object
, as explained by amit.
You can use this bit from the Google Guava library:
Collections.sort(list, Ordering.natural()
.onResultOf(new Function<String,YourClass>() {
public String call(YourClass o) {
return o.getName();
}))
.nullsLast();
The other answers which mention Comparator
are not incorrect, since Ordering
implements Comparator
. This solution is, in my opinion, a little easier, though it may be harder if you're a beginner and not used to using libraries and/or "functional programming".
Copied shamelessly from this answer on my own question.
public class ObjectComparator implements Comparator<Object> {
public int compare(Object obj1, Object obj2) {
return obj1.getName().compareTo(obj2.getName());
}
}
Please replace Object with your class which contains name field
Usage:
ObjectComparator comparator = new ObjectComparator();
Collections.sort(list, comparator);
You can use sortThisBy()
from Eclipse Collections:
MutableList<Campaign> list = Lists.mutable.empty();
list.sortThisBy(Campaign::getName);
If you can't change the type of list from List
:
List<Campaign> list = new ArrayList<>();
ListAdapter.adapt(list).sortThisBy(Campaign::getName);
Note: I am a contributor to Eclipse Collections.
@Victor's answer worked for me and reposting it here in Kotlin in case useful to someone else doing Android.
if (list!!.isNotEmpty()) {
Collections.sort(
list,
Comparator { c1, c2 -> //You should ensure that list doesn't contain null values!
c1.name!!.compareTo(c2.name!!)
})
}
If you are using a List<Object>
to hold objects of a subtype that has a name field (lets call the subtype NamedObject
), you'll need to downcast the list elements in order to access the name. You have 3 options, the best of which is the first:
List<Object>
in the first place if you can help it - keep your named objects in a List<NamedObject>
List<Object>
elements into a List<NamedObject>
, downcasting in the process, do the sort, then copy them backOption 3 would look like this:
Collections.sort(p, new Comparator<Object> () {
int compare (final Object a, final Object b) {
return ((NamedObject) a).getName().compareTo((NamedObject b).getName());
}
}