Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Constructor with Lambda expression (Set Comparator)

I am given the task to use the constructor TreeSet(Comparator<E> comparator) with a lambda expression to make the set be sorted by book title.

The following information is given:

public class Book implements Comparable<Book> {
    private String isbn;
    private String title;
    private String author;

    public int compareTo(Book obj) {
      return isbn.compareTo(obj.isbn);
    }
    // all-args constructor and getters
}

What I have thought about so far is: I think that the constructor allows you to define the Comparator. Perhaps I should do:

Comparator<String> comp = 
    (String title, String obj.title) -> (title.compareTo(obj.title));

Then put this comp into the TreeSet<Book> bookSet = new TreeSet<Book>(comp);

However, that doesn't seem to work. I think what I need to do is use the lambda expression in the same row when creating the new TreeSet, however, I am unsure how to do so.

like image 999
JavaMan Avatar asked Oct 18 '25 14:10

JavaMan


2 Answers

You need a Comparator<Book>, not a Comparator<String>. The easiest way to get one would be to use Comparator.comparing:

TreeSet<Book> bookSet = new TreeSet<>(Comparator.comparing(Book::getTitle));
like image 194
Mureinik Avatar answered Oct 20 '25 02:10

Mureinik


You're looking for a book comparator. Even if you're going to compare by book title, you'll still have to use Comparator<Book>.

To reuse your code, the correction you need is:

Comparator<Book> comp = 
    (Book book1, Book book2) -> (book1.getTitle().compareTo(book2.getTitle()));

Which can be rewritten as

Comparator<Book> comp = 
    (book1, book2) -> (book1.getTitle().compareTo(book2.getTitle()));

Or

Comparator<Book> comp = Comparator.comparing(Book::getTitle);

You can then pass comp as argument to TreeSet's constructor

like image 29
ernest_k Avatar answered Oct 20 '25 03:10

ernest_k