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?
Asked
Active
Viewed 113 times
-5
-
2take a look at the TreeSet – Enigo Apr 27 '16 at 19:36
-
1Write some code and show us. We'll help you debug it. – nicomp Apr 27 '16 at 19:37
-
1Does `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 – S Hristoskov Apr 28 '16 at 18:13print = new TreeSet (); for(Book a : books){ print.add(a); } for(Book b : print){ str += b.toString() +"\n"; } } return str; } -
@nicomp can you help – S Hristoskov Apr 28 '16 at 18:36
2 Answers
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.
-
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 – S Hristoskov Apr 28 '16 at 20:11print = new TreeSet (); for(Book a : books){ print.add(a); } for(Book b : print){ str += b.toString() +"\n"; } } return str; }