One-liner to count number of occurrences of String in a String[] in Java?
arrays, java
Solution
You can use the `frequency` method:
List<String> list = Arrays.asList(myArray);
int count = Collections.frequency(list, "B");
or in one line:
int count = Collections.frequency(Arrays.asList(myArray), "B");
With Java 8 you can also write:
long count = Arrays.stream(myArray).filter(s -> "B".equals(s)).count();
Or with a method reference:
long count = Arrays.stream(myArray).filter("B"::equals).count();
Problem
I have an array of `String`: ``` String[] myArray = {"A", "B", "B", "C"}; ``` Is there a quick way to count the number of occurrences of a string in that array? Yes, I know I can iterate and do the count myself: ``` int count = 0; String whatToFind = "B"; for (String s : myArray) { if (s.equals(whatToFind)) { ++count; } } ``` But I was wondering if there was a utility function for this. I couldn't find anything in `Arrays` or `ArrayUtils`. Is it possible to do this with a one-liner?