Krunal Khairnar
Krunal Khairnar

Reputation: 29

How to find the repeated occurrence of a substring in a String using the Java Stream API

public class Test {    
    public static void main(String[] args) {
       String str = "WELCOMEWELCOME";
       // find the occurance of 'CO' in the given string using stream API
    }
}

Upvotes: 2

Views: 363

Answers (1)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79540

You can use the stream and regex APIs as shown below to meet this requirement:

import java.util.regex.Pattern;

public class Main {
    public static void main(String args[]) {
        // find the occurance of 'CO' in the given string using stream API
        String str = "WELCOMEWELCOME";
        String substring = "CO";

        System.out.println(getSubstringCount(str, substring));
    }

    static long getSubstringCount(String str, String substring) {
        return Pattern.compile(Pattern.quote(substring))
                .matcher(str)
                .results()
                .count();
    }
}

Output:

2

ONLINE DEMO

I have updated the answer based on the following valuable comments from M. Justin:

The .map(MatchResult::group) call doesn't affect the subsequent .count, and so can be removed: Pattern.compile(substring).matcher(str).results().count().

If substring might contain characters with a special meaning in a pattern (e.g. *), getSubstringCount will need to escape them, e.g. Pattern.compile(Pattern.quote(substring)).

Upvotes: 6

Related Questions