Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One-liner to count number of occurrences of String in a String[] in Java?

Tags:

java

arrays

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?

like image 883
stackular Avatar asked Jul 18 '13 09:07

stackular


People also ask

How do you count occurrences of a string in Java?

First, we split the string by spaces in a. Then, take a variable count = 0 and in every true condition we increment the count by 1. Now run a loop at 0 to length of string and check if our string is equal to the word.

How do you count the number of occurrences of a character in a string?

The string count() method returns the number of occurrences of a substring in the given string. In simple words, count() method searches the substring in the given string and returns how many times the substring is present in it.


2 Answers

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();
like image 133
assylias Avatar answered Sep 28 '22 00:09

assylias


You can also try using Guava which is full of useful utilities. Using below code, you can count the frequency via Multiset:

public static void main(final String[] args) {
        String[] myArray = {"A", "B", "B", "C"};
        Multiset<String> wordsMultiset = HashMultiset.create();
        wordsMultiset.addAll(new ArrayList<String>(Arrays.asList(myArray)));
        int counts=wordsMultiset.count("B");
        System.out.println(counts);
    }

Although I know that you are looking for a single liner, but Guava is full of many more utils which are not possible with routine java utils.

like image 20
rahulserver Avatar answered Sep 28 '22 01:09

rahulserver