How to sort an ArrayList in Java
Implement Comparable interface to Fruit.
public class Fruit implements Comparable<Fruit> {
It implements the method
@Override
public int compareTo(Fruit fruit) {
//write code here for compare name
}
Then do call sort method
Collections.sort(fruitList);
Try BeanComparator from Apache Commons.
import org.apache.commons.beanutils.BeanComparator;
BeanComparator fieldComparator = new BeanComparator("fruitName");
Collections.sort(fruits, fieldComparator);
Use a Comparator
like this:
List<Fruit> fruits= new ArrayList<Fruit>();
Fruit fruit;
for(int i = 0; i < 100; i++)
{
fruit = new Fruit();
fruit.setname(...);
fruits.add(fruit);
}
// Sorting
Collections.sort(fruits, new Comparator<Fruit>() {
@Override
public int compare(Fruit fruit2, Fruit fruit1)
{
return fruit1.fruitName.compareTo(fruit2.fruitName);
}
});
Now your fruits list is sorted based on fruitName
.