Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a List<Object> alphabetically using Object name field

Tags:

java

list

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..?

like image 887
Saurabh Kumar Avatar asked Dec 08 '11 14:12

Saurabh Kumar


People also ask

How do you sort a list of objects based on an attribute of the objects in Java?

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.

How do I sort a list of custom objects?

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 .

Which method is used to sort object in list?

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.


1 Answers

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.

like image 194
Robert B Avatar answered Sep 19 '22 18:09

Robert B