How to filter String list by starting value in Java?

Java 8Object Oriented ProgrammingProgramming

Let’s first create a String list −

List list = new ArrayList<>();
list.add("wxy");
list.add("zabc");
list.add("ddd2");
list.add("def");
list.add("ghi");
list.add("wer");
list.add("uij");
list.add("wqy");

To filter String list by starting value, use filter() and startsWith() −

list.stream().filter((b) -> b.startsWith("w"))

The following is an example to filter string list by starting value −

Example

import java.util.ArrayList;
import java.util.List;
public class Demo {
   public static void main(final String[] args) {
      List list = new ArrayList<>();
      list.add("wxy");
      list.add("zabc");
      list.add("ddd2");
      list.add("def");
      list.add("ghi");
      list.add("wer");
      list.add("uij");
      list.add("wqy");
      System.out.println("List beginning with letter w = ");
      list.stream().filter((b) -> b.startsWith("w"))
      .forEach(System.out::println);
   }
}

Output

List beginning with letter w =
wxy
wer
wqy
raja
Published on 09-May-2019 08:53:24
Advertisements