user472221
user472221

Reputation: 3124

Sorting an ArrayList based on a field?

Hi I have an arrayList which has some objects.also my objects has two fields (1) name (2) cost I want to sort this arrayList with its cost field.is there any special method that do it for me or I should write it myself?also if there is some method for doeing this ,what is its time complexity(O(n),(O(nlogn))?

thanks

Upvotes: 0

Views: 663

Answers (3)

Sujith Surendranathan
Sujith Surendranathan

Reputation: 2579

You can use the Collections.sort() method for sorting, if you implement the Comparator interface for the objects which need to be compared.

Upvotes: 2

Steven
Steven

Reputation: 3894

If you like type saftey (not using BeanComparator), then you need to write your own comparator.

e.g.

Collections.sort(list, new Comparator<SomeType>() {
    public int compareTo(SomeType lhs, SomeType rhs) {
        return lhs.getCost().compareTo(rhs.getCost());
    }
});

Note, this is not null safe (can cost be null?).

The other option would be to use BeanComparator, but make sure you add a test which makes sure that the sorting always works in case the method name changes.

Upvotes: 4

camickr
camickr

Reputation: 324207

Check out the Bean Comparator for a couple of options.

Upvotes: 0

Related Questions