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
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())
.
Here is a version of Robert B's answer that works for List<T>
and sorting by a specified String property of the object using Reflection and no 3rd party libraries
/**
* Sorts a List by the specified String property name of the object.
*
* @param list
* @param propertyName
*/
public static <T> void sortList(List<T> list, final String propertyName) {
if (list.size() > 0) {
Collections.sort(list, new Comparator<T>() {
@Override
public int compare(final T object1, final T object2) {
String property1 = (String)ReflectionUtils.getSpecifiedFieldValue (propertyName, object1);
String property2 = (String)ReflectionUtils.getSpecifiedFieldValue (propertyName, object2);
return property1.compareToIgnoreCase (property2);
}
});
}
}
public static Object getSpecifiedFieldValue (String property, Object obj) {
Object result = null;
try {
Class<?> objectClass = obj.getClass();
Field objectField = getDeclaredField(property, objectClass);
if (objectField!=null) {
objectField.setAccessible(true);
result = objectField.get(obj);
}
} catch (Exception e) {
}
return result;
}
public static Field getDeclaredField(String fieldName, Class<?> type) {
Field result = null;
try {
result = type.getDeclaredField(fieldName);
} catch (Exception e) {
}
if (result == null) {
Class<?> superclass = type.getSuperclass();
if (superclass != null && !superclass.getName().equals("java.lang.Object")) {
return getDeclaredField(fieldName, type.getSuperclass());
}
}
return result;
}
Using a selection Sort
for(int i = list.size() - 1; i > 0; i--){
int max = i
for(int j = 0; j < i; j++){
if(list.get(j).getName().compareTo(list.get(j).getName()) > 0){
max= j;
}
}
//make the swap
Object temp = list.get(i);
list.get(i) = list.get(max);
list.get(max) = temp;
}
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.