Skip to content

Instantly share code, notes, and snippets.

@indrekots
Last active January 12, 2016 06:49
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save indrekots/d2b786ec2d5a9d9e66b4 to your computer and use it in GitHub Desktop.
public class BookFilterRunner {
public static void main(String[] args) {
//create a list of books
List<Book> books = new ArrayList<>();
books.add(new Book("Moby Dick", 250, "Herman Melville"));
books.add(new Book("Alice's Adventures in Wonderland", 190, "Lewis Carrol"));
books.add(new Book("Sylvie and Bruno", 400, "Lewis Carrol"));
//filter a list of books
filterBooks(books, "Lewis Carrol");
//filter the same list using Java 8 (lambda and Streams API)
books.stream().filter(b -> "Lewis Carrol".equals(b.getAuthor())).collect(toList());
}
//filtering a list of books before Java 8
public static List<Book> filterBooksByAuthor(List<Book> books, String author) {
List<Book> result = new ArrayList<>();
for (Book book : books) {
if (author.equals(book.getAuthor())) {
result.add(book);
}
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment