我有一个作者类是这样写的:
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的比较,这两个例子(1,2(。我是否正确实现了它?
我认为
,这是一个很好的实现。第二种方式是:
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());
}
}
你必须把它放在你的作者类中。以及要排序的位置:
List<Author> list = new ArrayList<>();
Collections.sort(list, new Author.AuthorComparator());