简体   繁体   中英

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?

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM