Last active
January 12, 2016 06:49
-
-
Save indrekots/d2b786ec2d5a9d9e66b4 to your computer and use it in GitHub Desktop.
Behavior parameterization http://blog.indrek.io/articles/java-8-behavior-parameterization/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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