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 = strings.stream()
	.filter(string -> string.endsWith("E"))
	.collect(Collectors.toList());
List<String> lengthMoreThenThree = strings.stream()
	.filter(string -> string.length() > 3)
	.collect(Collectors.toList());
List<String> bothConditions = strings.stream()
	.filter(string -> string.length() > 3 && string.endsWith("E"))
	.collect(Collectors.toList());

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 = 
	books.stream()
		.filter(book -> book.language.equals("French"))
		.collect(Collectors.toList());

Get English language books written by Pushkin

List<Book> englishLanguagePushkinBooks = 
	books.stream()
		.filter(book -> book.getLanguage().equals("English") 
			&& book.getAuthor().equals("Pushkin"))
		.collect(Collectors.toList());

Get Japan language books written by Pushkin that are favorite

List<Book> japanLanguagePushkinFavoriteListBooks = 
	books.stream()
		.filter(book -> book.getLanguage().equals("English")
			&& book.getAuthor().equals("Pushkin")
			&& isFavoriteBook(book))
		.collect(Collectors.toList());

You may also find these posts interesting: