我有一个像这样编写的Author类:
public final class Author implements Comparator<Author> {
private final String authorFirstname;
private final String authorLastname;
public Author(String authorFirstname, String authorLastname){
this.authorFirstname = authorFirstname;
this.authorLastname = authorLastname;
}
//Left out equals/HashCode
@Override
public int compare(Author o1, Author o2) {
// TODO Auto-generated method stub
return this.authorLastname.compareTo(o2.getLastname());
}
}
我想将它们存储在List
集合中,并按姓氏排序。我已阅读Java 8 comparable,这两个示例(1,2)。我是否正确实施了它?
答案 0 :(得分:0)
我认为,这是很好的实施。 第二种方式是:
List<Author> list = new ArrayList<>();
Collections.sort(list, new Comparator<Author>() {
@Override
public int compare(Author a1, Author a2) {
return a1.getLastName().compareTo(a2.getLastName());
}
});
并在您想要对此列表进行排序的地方使用它。
@Update,第三个选项:
public static class AuthorComparator implements Comparator<Author> {
@Override
public int compare(Author a1, Author a2) {
return a1.getLastName().compareTo(a2.getLastName());
}
}
您必须将它放在Author类中。 你想要排序的地方:
List<Author> list = new ArrayList<>();
Collections.sort(list, new Author.AuthorComparator());