我如何过滤以首字母开头的字符串值?
假设以下内容是我们的字符串列表 −
List list = Arrays.asList("Jonny", "David", "Tony", "Jacob", "Smith", "Bravo", "Gayle", "John");
现在过滤以首字母开头的字符串值 −
Stream stream = list.stream().filter(name -> name.startsWith("J"));
以下是一个过滤以首字母开头的字符串值的示例 −
示例
import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class Demo { public static void main(String[] args) { List list = Arrays.asList("Jonny", "David", "Tony", "Jacob", "Smith", "Bravo", "Gayle", "John"); System.out.println("List with elements..."); for (String res : list) { System.out.print(res+" "); } Stream stream = list.stream().filter(name -> name.startsWith("J")); System.out.println("
Getting strings beginning with letter J = "+stream.collect(Collectors.toList())); } }
输出
List with elements... Jonny David Tony Jacob Smith Bravo Gayle John Getting strings beginning with letter J = [Jonny, Jacob, John]
广告