Skip to content

Instantly share code, notes, and snippets.

@btforsythe
Created September 20, 2017 22:34
Show Gist options
  • Select an option

  • Save btforsythe/199cb6576cc59cf7c5221fa8f610331b to your computer and use it in GitHub Desktop.

Select an option

Save btforsythe/199cb6576cc59cf7c5221fa8f610331b to your computer and use it in GitHub Desktop.
Library - now with searching!
package library;
public class Book {
private String title;
private String isbn;
private String author;
private String category;
public String getTitle() {
return title;
}
public String getIsbn() {
return isbn;
}
public String getAuthor() {
return author;
}
public String getCategory() {
return category;
}
public Book(String title, String isbn, String author, String category) {
this.title = title;
this.isbn = isbn;
this.author = author;
this.category = category;
}
}
package library;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class Library {
Map<String, Book> booksByIsbn = new HashMap<String, Book>();
// here I'm using the diamond operator
Map<String, Set<Book>> booksByCategory = new HashMap<>();
public void addBook(Book book) {
booksByIsbn.put(book.getIsbn(), book);
String category = book.getCategory();
// if the category isn't already in the map
if(!booksByCategory.containsKey(category)) {
// put a new set into the map
booksByCategory.put(category, new HashSet<>());
}
Set<Book> booksForCg = booksByCategory.get(category);
booksForCg.add(book);
}
public Set<Book> findBooksInCategory(String category) {
return booksByCategory.get(category);
}
public Set<Book> searchTitles(String substring) {
Set<Book> matchingBooks = new HashSet<>();
for(Book b: booksByIsbn.values()) {
if(b.getTitle().contains(substring)) {
matchingBooks.add(b);
}
}
return matchingBooks;
}
}
package library;
import java.util.Set;
public class LibraryApp {
public static void main(String[] args) {
Library myLibrary = new Library();
String title = "The Great Gatsby";
String isbn = "178139685X";
String author = "F. Scott Fitzgerald";
String category = "Classics";
Book gatsby = new Book(title, isbn, author, category);
myLibrary.addBook(gatsby);
myLibrary.addBook(new Book("To Kill A Mockingbird", "iMadeItUpIsbn", "Harper Lee", "Classics"));
Set<Book> classicsBooks = myLibrary.findBooksInCategory("Classics");
System.out.println("Classics:");
for(Book b: classicsBooks) {
System.out.println(b.getTitle());
}
System.out.println("Books whose titles contain 'Great':");
Set<Book> booksWithGreat = myLibrary.searchTitles("Great");
for(Book b: booksWithGreat) {
System.out.println(b.getTitle());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment