Count occurrence of ArrayList broken into groups

Pam :

I'm trying to figure out how to count the occurrence of an element in an ArrayList that's being broken up by dashes ---.

ArrayList<String> animals = new ArrayList<String>();
animals.add("dog");
animals.add("cat");
animals.add("bat");
animals.add("bat");
animals.add("---");
animals.add("cat");
animals.add("dog");
animals.add("dog");
animals.add("---");
animals.add("bat");
animals.add("bat");
animals.add("dog");

So my ArrayList looks like this:

animals = {"dog", "cat", "bat", "bat", "---", "cat", "dog", "dog", "---", "bat", "bat", "dog"}

And I want my output to (alphabetically) look like this:

bat: 2
cat: 1
dog: 1
---
cat: 1
dog: 2
---
bat: 2
dog: 1

Before I had the dashes, I was getting the occurrence by using this

int occurrences = Collections.frequency(animals, "bat");

Any idea how I can achieve this?

Karol Dowbecki :

It mostly depends on how do you plan to use the frequency for each value. If the objective is just to print it, then following:

SortedMap<String, Integer> freq = new TreeMap<>(); // to sort keys alphabetically
for (String animal : animals) {
  if (animal.equals("---")) {
    System.out.println(freq);
    freq.clear();
  } else {
    freq.merge(animal, 1, Integer::sum);
  }
}
System.out.println(freq);

will output:

{bat=2, cat=1, dog=1}
{cat=1, dog=2}
{bat=2, dog=1}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=110574&siteId=1