Reputation: 45
This is my main class: public class Main {
public static void main(String[] args) throws BookNotFoundException {
// TODO Auto-generated method stub
//Library library = new Library();
LibraryHashMap libhmap = new LibraryHashMap();
// Adding books
libhmap.addBook(new Book(1, "The Great Gatsby", "F. Scott Fitzgerald"));
libhmap.addBook(new Book(2, "1984", "George Orwell"));
libhmap.addBook(new Book(3, "To Kill a Mockingbird", "Harper Lee"));
libhmap.addBook(new Book(4, "Oliver Twist", "Charles Dickens"));
libhmap.addBook(new Book(5, "Harry Potter Series", "J.K. Rowling"));
libhmap.addBook(new Book(6, "Death on the nile", "Agatha Christy"));
libhmap.addBook(new Book(7, "Murder on the Orient Express", "Agatha Christy"));
libhmap.addBook(new Book(8, "A Christmas Carol", "Charles Dickens"));
// Display all books
System.out.println("=== Display All Books ===");
libhmap.displayBooks();
}
Library class: public class LibraryHashMap {
private Map<Integer, Book> books; // Collection to store books
// Constructor
public LibraryHashMap() {
this.books = new HashMap<>();
}
// Add a book to the library
public void addBook(Book book) {
books.put(book.getID(),book);
System.out.println("Book added: " + book.getTitle());
}
// Display all books in the library
public void displayBooks() {
if (books.isEmpty()) {
System.out.println("The library is empty.");
} else {
System.out.println("Books in the library:");
for (Map.Entry<Integer, Book> entry : books.entrySet()) {
System.out.println("Book ID: "+entry.getKey()+" Book name: "+entry.getValue());
}
}
}
}
Book Class: public class Book {
private int id;
private String title;
private String author;
public Book(int id, String title, String author) {
this.id = id;
this.title = title;
this.author = author;
}
public int getID() {
return id;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public String toString() {
return "Book ID:"+id+" Book Title:"+title+" Book Author:"+author;
}
}
Now, I want to write a function to list all unique authors in the library by introducing TreeSet or HashSet since both these collections stores unique elements only . I believe I have to use the getAuthor() function but somehow I am not how to construct it. Please let me know how to do that?
Upvotes: 0
Views: 9