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<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
Get English language books written by Pushkin
Get Japan language books written by Pushkin that are favorite
You may also find these posts interesting: