Trevor
Trevor

Reputation: 101

Java: How do I sort an ArrayList according to a natural ordering?

I have an ArrayList of instances of a class I created, each of which contains a single field with a String. I have implemented Comparable in the class I created. How do I sort the Array List?

Upvotes: 1

Views: 10354

Answers (2)

Nestor Milyaev
Nestor Milyaev

Reputation: 6595

Or you can use Java 8 API:

List<MyGene> l = new ArrayList<MyGene>();
l.stream().sorted().collect(toList());

Typically, you'd use something like that:

 List<MyGene> l = new ArrayList<MyGene>();
 l.stream().sorted((o1, o2) -> o2.getId().compareTo(o1.getId())).collect(toList());

, but since your MyGene already implements comparable, simple sorted() should suffice.

Upvotes: 2

Nikita Rybak
Nikita Rybak

Reputation: 67986

Collections.sort

edit
No errors for me

class Gene {
}
class MyGene extends Gene implements Comparable<MyGene> {
    public int compareTo(MyGene o) {
        throw new UnsupportedOperationException("Method is not implemented yet.");
    }
}

...

    List<MyGene> l = new ArrayList<MyGene>();
    Collections.sort(l);

Upvotes: 7

Related Questions