I have a List of Objects like List<Object> p
.I want to sort this list alphabetically using Object name field. Object contains 10 field and name field is one of them.
if (list.size() > 0) { Collections.sort(list, new Comparator<Campaign>() { @Override public int compare(final Object object1, final Object object2) { return String.compare(object1.getName(), object2.getName()); } } ); }
But there is nothing like String.compare..?
sort() method to sort a list of objects using some examples. By default, the sort() method sorts a given list into ascending order (or natural order). We can use Collections. reverseOrder() method, which returns a Comparator, for reverse sorting.
In the main() method, we've created an array list of custom objects list , initialized with 5 objects. For sorting the list with the given property, we use list 's sort() method. The sort() method takes the list to be sorted (final sorted list is also the same) and a comparator .
sort() method are used to sort the list of objects in Java. compare() and compareTo() method of Comparator and Comparable interface provides comparison logic needed for sorting objects.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With