Reputation: 101
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
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
Reputation: 67986
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