How do I split a string using Pattern.splitAsStream() method?

Pattern.splitAsStream() in Java is a method that allows us to split a string into a stream of substrings given a regex pattern. This can be useful when we’re working with large strings, and we want to process the substrings in a functional style using Java Streams.

Here’s a basic example of how you can use the Pattern.splitAsStream() method:

package org.kodejava.regex;

import java.util.regex.Pattern;
import java.util.stream.Stream;

public class SplitAsStreamExample {
    public static void main(String[] args) {
        Pattern pattern = Pattern.compile(",");
        String testStr = "one,two,three,four,five";
        Stream<String> words = pattern.splitAsStream(testStr);
        words.forEach(System.out::println);
    }
}

In this example, the pattern is a comma (,), and it is used to split the testStr string in the splitAsStream() call. This creates a Stream of strings. Each element in the stream is a substring of testStr that falls between the commas. The Stream.forEach() method is then used to print out each of these substrings. You can replace the comma with any regex pattern based on your requirements.

The result will be:

one
two
three
four
five

Consider a situation where we have a CSV (Comma Separated Values) file. We need to read the file, process each line and extract the fields. For this purpose, let’s use the BufferedReader, Pattern.splitAsStream(), and Java 8’s Stream API:

package org.kodejava.regex;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

public class CSVProcessor {
    public static void main(String[] args) {
        Pattern pattern = Pattern.compile(",");
        String pathToFile = "country.csv";

        try (BufferedReader reader = new BufferedReader(new FileReader(pathToFile))) {
            List<String[]> records = reader.lines()
                    .map(line -> pattern.splitAsStream(line).toArray(String[]::new))
                    .toList();

            // Print each record
            records.forEach(record -> System.out.println(Arrays.toString(record)));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In this code snippet, we are reading a file line by line using a BufferedReader. Then for each line, we are splitting it into a Stream of fields using Pattern.splitAsStream(). This produces a Stream of fields for each line of the file. We then collect the fields into a list of String arrays, with each array representing a line in the CSV (as split by commas).

Finally, we print out each record (which is a String array) to the console.

Remember that Pattern.splitAsStream() returns a stream of String and we can use it effectively in a functional programming style, and it integrates very well with the Java’s Stream API.

How to split a string by a number of characters?

The following code snippet will show you how to split a string by numbers of characters. We create a method called splitToNChars() that takes two arguments. The first arguments is the string to be split and the second arguments is the split size.

This splitToNChars() method will split the string in a for loop. First we’ll create a List object that will store parts of the split string. Next we do a loop and get the substring for the defined size from the text and store it into the List. After the entire string is read we convert the List object into an array of String by using the List‘s toArray() method.

Let’s see the code snippet below:

package org.kodejava.lang;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class SplitStringForEveryNChar {
    public static void main(String[] args) {
        String text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

        System.out.println(Arrays.toString(splitToNChar(text, 3)));
        System.out.println(Arrays.toString(splitToNChar(text, 4)));
        System.out.println(Arrays.toString(splitToNChar(text, 5)));
    }

    /**
     * Split text into n number of characters.
     *
     * @param text the text to be split.
     * @param size the split size.
     * @return an array of the split text.
     */
    private static String[] splitToNChar(String text, int size) {
        List<String> parts = new ArrayList<>();

        int length = text.length();
        for (int i = 0; i < length; i += size) {
            parts.add(text.substring(i, Math.min(length, i + size)));
        }
        return parts.toArray(new String[0]);
    }
}

When run the code snippet will output:

[ABC, DEF, GHI, JKL, MNO, PQR, STU, VWX, YZ]
[ABCD, EFGH, IJKL, MNOP, QRST, UVWX, YZ]
[ABCDE, FGHIJ, KLMNO, PQRST, UVWXY, Z]

How do I split a string with multiple spaces?

This code snippet show you how to split string with multiple white-space characters. To split the string this way we use the "\s+" regular expression. The white-space characters include space, tab, line-feed, carriage-return, new line, form-feed.

Let’s see the code snippet below:

package org.kodejava.lang;

import java.util.Arrays;

public class SplitStringMultiSpaces {
    public static void main(String[] args) {
        String text = "04/11/2021    SHOES      RUNNING RED   99.9 USD";

        // Split the string using the \s+ regex to split multi spaces
        // line of text.
        String[] items = text.split("\\s+");
        System.out.println("Length = " + items.length);
        System.out.println("Items  = " + Arrays.toString(items));
    }
}

The result of the code snippet is:

Length = 6
Items  = [04/11/2021, SHOES, RUNNING, RED, 99.9, USD]

How do I break a paragraph into sentences?

This example show you how to use the BreakIterator.getSentenceInstance() to breaks a paragraphs into sentences that composes the paragraph. To get the BreakIterator instance we call the getSentenceInstance() factory method and passes a locale information.

In the count(BreakIterator bi, String source) method we iterate the break to extract sentences that composes the paragraph which value is stored in the paragraph variable.

package org.kodejava.text;

import java.text.BreakIterator;
import java.util.Locale;

public class BreakSentenceExample {
    public static void main(String[] args) {
        String paragraph = """
                Line boundary analysis determines where a text \
                string can be broken when line-wrapping. The \
                mechanism correctly handles punctuation and \
                hyphenated words. Actual line breaking needs to \
                also consider the available line width and is \
                handled by higher-level software.
                """;

        BreakIterator iterator = BreakIterator.getSentenceInstance(Locale.US);

        int sentences = count(iterator, paragraph);
        System.out.println("Number of sentences: " + sentences);
    }

    private static int count(BreakIterator bi, String source) {
        int counter = 0;
        bi.setText(source);

        int lastIndex = bi.first();
        while (lastIndex != BreakIterator.DONE) {
            int firstIndex = lastIndex;
            lastIndex = bi.next();

            if (lastIndex != BreakIterator.DONE) {
                String sentence = source.substring(firstIndex, lastIndex);
                System.out.println("sentence = " + sentence);
                counter++;
            }
        }
        return counter;
    }
}

Our program will print the following result on the console screen:

sentence = Line boundary analysis determines where a text string can be broken when line-wrapping. 
sentence = The mechanism correctly handles punctuation and hyphenated words. 
sentence = Actual line breaking needs to also consider the available line width and is handled by higher-level software.

Number of sentences: 3

How do I break a text or sentence into words?

At first, it might look simple. We can just split the text using the String.split(), the word is split using space. But what if a word ends with questions marks (?) or exclamation marks (!) instead? There might be some other rules that we also need to care.

Using the java.text.BreakIterator makes it much simpler. The class’s getWordInstance() factory method creates a BreakIterator instance for words break. Instantiating a BreakIterator and passing a locale information makes the iterator to breaks the text or sentence according the rule of the locale. This is really helpful when we are working with a complex language such as Japanese or Chinese.

Let us see an example of using the BreakIterator below.

package org.kodejava.text;

import java.text.BreakIterator;
import java.util.Locale;

public class BreakIteratorExample {
    public static void main(String[] args) {
        String data = "The quick brown fox jumps over the lazy dog.";
        String search = "dog";

        // Gets an instance of BreakIterator for word break for the
        // given locale. We can instantiate a BreakIterator without
        // specifying the locale. The locale is important when we
        // are working with languages like Japanese or Chinese where
        // the breaks standard may be different compared to English.
        BreakIterator bi = BreakIterator.getWordInstance(Locale.US);

        // Set the text string to be scanned.
        bi.setText(data);

        // Iterates the boundary / breaks
        System.out.println("Iterates each word: ");
        int count = 0;
        int lastIndex = bi.first();
        while (lastIndex != BreakIterator.DONE) {
            int firstIndex = lastIndex;
            lastIndex = bi.next();

            if (lastIndex != BreakIterator.DONE
                    && Character.isLetterOrDigit(data.charAt(firstIndex))) {
                String word = data.substring(firstIndex, lastIndex);
                System.out.printf("'%s' found at (%s, %s)%n",
                        word, firstIndex, lastIndex);

                // Counts how many times the word dog occurs.
                if (word.equalsIgnoreCase(search)) {
                    count++;
                }
            }
        }

        System.out.println("Number of word '" + search + "' found = " + count);
    }
}

Here are the program output:

Iterates each word: 
'The' found at (0, 3)
'quick' found at (4, 9)
'brown' found at (10, 15)
'fox' found at (16, 19)
'jumps' found at (20, 25)
'over' found at (26, 30)
'the' found at (31, 34)
'lazy' found at (35, 39)
'dog' found at (40, 43)
Number of word 'dog' found = 1