Tuesday, July 12, 2011

How to sort array list?

Sort by simple type property

1. Implement the Comparable interface


public class Item implements Comparable<Item> {

}

2. Implement the compareTo method.


@Override
public int compareTo(Item another) {
//Compare the name
return this.name.compareTo(another.name);
}

3. Call sort


List<Item> items = ..
items.sort();

Sort by user defined property

1. Create a new class


import java.util.Comparator;
public class ItemCompareByLocation implements Comparator<Item>{
@Override
public int compare(Item arg0, Item arg1) {
return arg0.getLocation().compareTo(arg1.getLocation());
}
}

2. Call sort


Collections.sort(items, new ItemCompareByLocation());

No comments:

Post a Comment