Java 8 Pattern SplitAsStream method

Java 8 Pattern SplitAsStream method

In this example, we will learn about the Java8 splitAsStream method of the Pattern class. As you have face this scenario many times that you have a string variable and you want to split that.

For Example

String names = "vasu, ayush, sushmita, konika";

Now you want to split this string variable using “,” .

so the old approach that we use before java8 is the split() method.

String[] splitNames = names.split(",");

This is a very bad choice if we use the split() method because we have to avoid the array as much as we can in our code.

So the alternate of split() method is splitAsStream(). splitAsStream belongs to the Pattern class.

Note: If you want to use splitAsStream() method of Pattern class then you must have Java 8 or higher version installed.

splitAsStream() is used to return the stream of String instead of String array. So if we want to split the above String names variable and store the result as a list of strings. So we can use the below syntax :

String names = "vasu, Ayush, Sushmita, Konika";
List<String> splitNames = Pattern.compile(",").splitAsStream(names).collect(Collectors.toList());
splitNames.forEach(System.out::println);
Java 8 Pattern SplitAsStream

Now we know that pattern class resides in java.util.regex package. And it has a method splitAsStream(). This method is used to split the string using the given expression and return the Stream of the list as a result.

Syntax of splitAsStream() method

public Stream<String> splitAsStream(final CharSequence input)

It accepts the CharSequence in our example it is the names variable and returns the Stream of String as a result. In our example, it is returning List<String>.

Example 2:

Now suppose you have to split your string using : expression instead of ,

String names = "vasu:Ayush:Sushmita:Konika";
List<String> splitNames = Pattern.compile(":").splitAsStream(names).collect(Collectors.toList());
splitNames.forEach(System.out::println);

Output

splitAsStream java8

Example 3:

If you have to split your string from a specific word.

String names = "I like JavaDream it has a cool content";
List<String> splitNames = Pattern.compile("JavaDream").splitAsStream(names).collect(Collectors.toList());
splitNames.forEach(System.out::println);

Output

pattern java 8

You may also like:

Optional in java 8 tutorial with Example

Spring Batch Complete Tutorial with example.

Json Parser in Java Complete Example

Help Others, Please Share

Leave a Reply

Your email address will not be published. Required fields are marked *

x