0

I am new to the streams and I have the requirement to count a particular String in each line of a text file using Java 8 Stream. Does anyone have any suggestions or sample code? Edit: I missed to add my sample code..Here is the code I have just started but I have no clue as how to use count() on the stream.

Stream<String> lines=Files.lines(Paths.get("M:\\GIT_CODE\\FIRE_CHAT_PARSE\\New Text Document.txt"));

lines.map(eachLine-> spliteLineToArrayofSTrFunc(eachLine)).forEach(eachLines->{
        System.out.println(eachLines);  
        System.out.println();   
});
        
private static Function<String, String[]> spliteLineToArrayofSTrFunc(String line) {
        return (String lines)->{
            System.out.println();
            return line.split(" ");
        };
}
6
  • 1
    What have you tried so far? Please share your attempts and ask a more specific question. Commented Aug 22, 2020 at 15:11
  • Suggestion: Look for a terminal operation named count under the Stream class. But remember, you might want to filter specific string before you count. Commented Aug 22, 2020 at 15:14
  • Try something first, and then post the problems you face. Commented Aug 22, 2020 at 15:15
  • I missed to put my code. Just edited my question. Commented Aug 22, 2020 at 15:24
  • 2
    Let's say you want to find the string lapse? Do you want the count to include the word collapse? What if the line includes the string more than once? You need to be specific in what you want. Perhaps show some examples. Commented Aug 22, 2020 at 15:52

1 Answer 1

1

If your question is about finding exact match with words separated by whitespace and also including words ending with . then you can do something like -

long count =
    strings.stream()
        .flatMap(str -> Arrays.stream(str.split("[\\s\\.]+")))
        .filter(str -> str.equals(wordToSearch))
        .count();

For below 2 lines, if you search for word stream then you'll get 3 as count.

I am new to the stream and I have the requirement to count a particular String in each line of a text file using Java 8 stream. 
Does anyone have any stream suggestions or sample code? Edit: I missed to add my sample code.
Sign up to request clarification or add additional context in comments.

1 Comment

You can avoid the temporary array created by split by using .flatMap(Pattern.compile("[\\s\\.]+" )::splitAsStream). This will also avoid compiling the regex pattern for every line.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.