按姓氏排序列表

Sort list my lastname

我有一个作者 class 是这样写的:

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, these two examples(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());
    }
});

然后在您要对列表进行排序的地方使用它。

@更新,第三个选项:

public static class AuthorComparator implements Comparator<Author> {
   @Override
   public int compare(Author a1, Author a2) {
       return a1.getLastName().compareTo(a2.getLastName());
   }
}

你必须把它放在你的作者中 class。 以及您要排序的位置:

List<Author> list = new ArrayList<>();
Collections.sort(list, new Author.AuthorComparator());