-5

I have Object called Book with String author , title. I use Collection of Books (Collection) and want to print a list of all books , but in alphabetically order of author and when I have 2 or more books from one author than alphabetically order of title . How can I make this?

S Hristoskov
  • 53
  • 1
  • 9
  • 2
    take a look at the TreeSet – Enigo Apr 27 '16 at 19:36
  • 1
    Write some code and show us. We'll help you debug it. – nicomp Apr 27 '16 at 19:37
  • 1
    Does `Book` implement `Comparable`? – Makoto Apr 27 '16 at 19:37
  • I have Collection and want to make string with all the book.toString() . I tried to add them in a new TreeSet but it doesnt work. here is my code : public String toString(){ String str = ""; if(books.size()==0) return "Empty Library"; else { Set print = new TreeSet(); for(Book a : books){ print.add(a); } for(Book b : print){ str += b.toString() +"\n"; } } return str; } – S Hristoskov Apr 28 '16 at 18:13
  • @nicomp can you help – S Hristoskov Apr 28 '16 at 18:36

2 Answers2

1

To sort T, it needs to extend from Comparable.This is:T extends Comparable<T>.

Then, implement the compareTo method and then you may be able to compare the items for the sorting.

Felipe Sulser
  • 1,185
  • 8
  • 19
1

You could use a sortedSet. You may check this answer for help.

Community
  • 1
  • 1
Nick
  • 966
  • 1
  • 10
  • 20
  • I have Collection and want to make string with all the book.toString() . I tried to add them in a new TreeSet but it doesnt work. here is my code : public String toString(){ String str = ""; if(books.size()==0) return "Empty Library"; else { Set print = new TreeSet(); for(Book a : books){ print.add(a); } for(Book b : print){ str += b.toString() +"\n"; } } return str; } – S Hristoskov Apr 28 '16 at 20:11