Pattern splitAsStream() method in Java with examples

JavaObject Oriented ProgrammingProgramming

The Pattern class of the java.util.regex package is a compiled representation of a regular expression.

The splitAsStream() method of this class accepts a CharSequence object, representing the input string as a parameter and, at each match, it splits the given string into a new substring and returns the result as a stream holding all the substrings.


import java.util.regex.Pattern;
public class SplitAsStreamMethodExample {
   public static void main( String args[] ) {
      //Regular expression to find digits
      String regex = "(\s)(\d)(\s)";
      String input = " 1 Name:Radha, age:25 2 Name:Ramu, age:32" + " 3 Name:Rajeev, age:45 4 Name:Raghu, age:35" + " 5 Name:Rahman, age:30";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);
      //verifying whether match occurred
         System.out.println("Given String contains digits");
         System.out.println("Given String does not contain digits");
      //Splitting the string
      Stream<String> stream = pattern.splitAsStream(input);
      Object obj[] = stream.toArray();
      for(int i=0; i< obj.length; i++) {


Given String contains digits
Name:Radha, age:25
Name:Ramu, age:32
Name:Rajeev, age:45
Name:Raghu, age:35
Name:Rahman, age:30
Updated on 20-Nov-2019 05:52:46