Skip to content

Instantly share code, notes, and snippets.

@magouyaware
Last active April 21, 2017 20:04
Show Gist options
  • Save magouyaware/4d0e70a7c0890e9770367b3f528d9ae8 to your computer and use it in GitHub Desktop.
Save magouyaware/4d0e70a7c0890e9770367b3f528d9ae8 to your computer and use it in GitHub Desktop.
import java.util.*;
public class Library
{
public List<String> filterBooks(HashMap<String, Boolean> library, IBookFilter bookFilter)
{
List<String> filteredBooks = new ArrayList<String>();
for (Map.Entry<String, Boolean> entry : library.entrySet())
{
String bookTitle = entry.getKey();
if (bookFilter.keep(bookTitle, entry.getValue())
filteredBooks.add(bookTitle);
}
return filteredBooks;
}
public void printBooks(String listTitle, List<String> books)
{
System.out.println(listTitle);
System.out.println("-------------------------------");
if (books.isEmpty())
System.out.println("No books to display!");
for (String book : books)
System.out.println(book);
System.out.println("");
}
public interface IBookFilter
{
boolean keep(String book, boolean finished);
}
public static void main(String[] args)
{
// Filter to get only finished books
IBookFilter finishedFilter = new IBookFilter()
{
public boolean keep(String book, boolean finished)
{
return finished;
}
};
// Filter to get only unfinished books
IBookFilter unfinishedFilter = new IBookFilter()
{
public boolean keep(String book, boolean finished)
{
return !finished;
}
};
// Filter to get only books with the word "the" in the title
IBookFilter booksWithTheFilter = new IBookFilter()
{
public boolean keep(String book, boolean finished)
{
return book.toLowerCase().contains("the");
}
};
HashMap<String, Boolean> myBooks = new HashMap<String, Boolean>;
myBooks.put("Road Down the Funnel", true);
myBooks.put("Rat: A Biology", false);
myBooks.put("The Wizard of Oz", false);
myBooks.put("TimeIn", true);
myBooks.put("3D Food Printing", false);
Library myLibrary = new Library();
List<String> finishedBooks = myLibrary.filterBooks(myBooks, finishedFilter);
List<String> unfinishedBooks = myLibrary.filterBooks(myBooks, unfinishedFilter);
List<String> booksWithThe = myLibrary.filterBooks(myBooks, booksWithTheFilter);
myLibrary.printBooks("Finished Books", finishedBooks);
myLibrary.printBooks("Unfinished Books", unfinishedBooks);
myLibrary.printBooks("Books with the word \"the\"", booksWithThe);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment