1

I have an Author class written like this:

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

}

I want to store them in a List collection and sort them by last name. I've read Java 8 comparable, these two examples(1,2). Have I implemented it correctly?

Community
  • 1
  • 1
  • 2
    Generally, a `compareTo` method on an object should be the canonical and most common comparison for the object. A better option is to use `Comparator.comparing(Author::getLastname)` for when you want a more specific comparator. – 4castle May 11 '17 at 23:18
  • suppose you refer this [post](https://www.mkyong.com/java8/java-8-lambda-comparator-example/) on java 8 comparator. – Rajith Pemabandu May 11 '17 at 23:24
  • To add on to @4castle's point, it's recommended that comparable classes be *consistent with equals*, meaning that `a.compareTo(b) == 0` should always be equal to `a.equals(b)`. I suspect that's not the case here. – shmosel May 11 '17 at 23:30
  • @shmosel - I want to sort the authors by lastname, how would I do it? –  May 11 '17 at 23:32
  • 1
    `authors.sort(Comparator.comparing(Author::getLastName));` – shmosel May 11 '17 at 23:32
  • @shmosel - Check my updated code. How about now? –  May 11 '17 at 23:34
  • Very unusual. Was there a problem with my suggestion? – shmosel May 11 '17 at 23:43
  • @shmosel - I don't understand what you suggested. Perhaps a full code sample? –  May 11 '17 at 23:44
  • 1
    It's a full solution. It does exactly what you asked for - sorts a list of authors by last name. What's the problem? – shmosel May 11 '17 at 23:45

1 Answers1

0

I think, that it's good implemetation. Second way is:

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

And use this in place where you want to sort this list.

@Update, third option:

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

You have to put this in your Author class. And where you want to sort:

List<Author> list = new ArrayList<>();
Collections.sort(list, new Author.AuthorComparator());
Kutti
  • 486
  • 1
  • 6
  • 17