The example uses java 8 stream to filter a String value with starting letter say 'S'.
Create a stream from a list of names. In the stream use the filter method. The filter will return a Stream of String. The filtered names should be collected in a List to print the result.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class FilterNames {
public static void main(String[] args) {
List<String> names = Arrays.asList("Ava", "Alberto", "Sarah", "Sam", "Smith");
names = names.stream().filter(s -> s.startsWith("S")).collect(Collectors.toList());
for (String name : names) {
System.out.println("Names Start with S: " + name);
}
}
}
Make sure to assign the collected list to the List of String.
Output:
Names Start with S: Sarah
Names Start with S: Sam
Names Start with S: Smith
Using forEach
Use forEach to print the name.
public static void main(String[] args) {
List<String> names = Arrays.asList("Ava", "Alberto", "Sarah", "Sam", "Smith");
names = names.stream().filter(s -> s.startsWith("S")).collect(Collectors.toList());
names.forEach(System.out::println);
}
Output:
Sarah
Sam
Smith
By assigning filter to Stream and printing the final list
public static void main(String[] args) {
List<String> names = Arrays.asList("Ava", "Alberto", "Sarah", "Sam", "Smith");
Stream<String> namesStartsWith = names.stream().filter(s -> s.startsWith("S"));
System.out.println(namesStartsWith.collect(Collectors.toList()));
}
Output
[Sarah, Sam, Smith]