Filter list of strings with Java 8 stream.filter()

We start with the simpliest example - list of strings. We are going to implement filters based on different conditions

List<String> strings =  Arrays.asList("ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN");

List<String> endsWithE =
	.filter(string -> string.endsWith("E"))
List<String> lengthMoreThenThree =
	.filter(string -> string.length() > 3)
List<String> bothConditions =
	.filter(string -> string.length() > 3 && string.endsWith("E"))

System.out.println("List of Strings ending with E: " + endsWithE);
System.out.println("List of Strings with length more then 3: " + lengthMoreThenThree);
System.out.println("List of Strings - both conditions: " + bothConditions);

Output for filtered lists of strings

List of Strings ending with E: [ONE, THREE, FIVE]
List of Strings with length more then 3: [THREE, FOUR, FIVE, SEVEN]
List of Strings - both conditions: [THREE, FIVE]

Java 8. stream.filter

List<Integer>, List<Long> and other boxed primitives can be sorted same way.

Filter list of objects with Java 8 stream.filter(). Examples

Get only French language books

List<Book> frenchLangageBooks =
		.filter(book -> book.language.equals("French"))

Get English language books written by Pushkin

List<Book> englishLanguagePushkinBooks =
		.filter(book -> book.getLanguage().equals("English") 
			&& book.getAuthor().equals("Pushkin"))

Get Japan language books written by Pushkin that are favorite

List<Book> japanLanguagePushkinFavoriteListBooks =
		.filter(book -> book.getLanguage().equals("English")
			&& book.getAuthor().equals("Pushkin")
			&& isFavoriteBook(book))

You may also find these posts interesting: