Hi i want to count how many time a String is found in a Array of Strings using Streams
What i have thought so far is this:
Stream<String> stream=Arrays.stream(array);
int counter= (int) stream.filter(c-> c.contains("something")).count();
return counter;
The problem that i get is that most of the time i get an error of NullPointerException and i think is because of .count() if it doesn't get any much inside filter(c-> c.contains("something")).
And i came to this conclusion cause if i run it with out .count() like that stream.filter(c-> c.contains("something")); without returning nothing, it won't throw an Exception. I'm not sure about it but that's what i think.
Any ideas on how i can count the times a String appears in and Array of Strings using Streams?
.count()it won't throw an Exception" that's because withoutcountthe pipeline is not executed. streams are lazy. my bet would be onci.e. the elements inside the array. you're better off showing the stack trace to better explain your issue.arraycome from? it looks the problem is from that.int? Doesn'tlongmeet your requirements? However, you can add a second filter that does.filter(java.util.Objects::nonNull)before the filter you already have applied.NullPointerExceptionwhencountis not called then what you've just suggested is not the culprit. see my answer for more info on that.