Count identical strings in array for each unique entry

If I have an array of strings, how do I count the number of times each unique string occurs in the array? I do not know the content of the array beforehand.

Look at HashMap please.

Store the words in the HashMap.

  • When a entry is there already, increment its value by 1,
  • otherwise make a new entry

https://www.processing.org/reference/HashMap.html

Chrisir

1 Like

Awesome, would you do it like this?

import java.util.Map;
HashMap<String,Integer> hm = new HashMap<String,Integer>();
String[] myStrings = {"dog", "dog", "cat", "dog"};

for (int i = 0; i<myStrings.length; i++) {
  int count = hm.containsKey(myStrings[i]) ? hm.get(myStrings[i]) : 0;
  hm.put(myStrings[i],count+1);  
}
println(hm);

There are many ways to do it. Here’s an interesting 1 using StringList + IntDict:

// https://Discourse.Processing.org/t/
// count-identical-strings-in-array-for-each-unique-entry/16678/4

// GoToLoop (2019/Dec/28)

final String[] animalsArray = {
  "cat", "dog", "ferret", "ferret", "cat", "parrot", "dog", "macaw", "cat"
};
println(animalsArray);

final StringList animalsList = new StringList(animalsArray);
println(animalsList);

final IntDict animalsTally = animalsList.getTally();
println(animalsTally);

final String[] animalsUnique = animalsList.getUnique();
println(animalsUnique);

exit();
1 Like

@AndreasRef

looks great!

same sketch


import java.util.Map;

HashMap<String, Integer> hm = new HashMap<String, Integer>();

String[] myStrings = {
  "dog", "dog", "cat", "dog", "bird"
};

void setup() {
  size(600, 600); 
  background(0); 

  addWordsToHashMap(myStrings);
}

void draw() {
  background(0); 

  showHashMap();
}

// ---------------------------------------------------------------------

void addWordsToHashMap(String[] myStrings) {
  for (int i = 0; i<myStrings.length; i++) {
    // if it's old
    if (hm.containsKey(myStrings[i])) {
      // increase
      increaseHashMapByOne(myStrings[i]);
    } else { 
      // add
      addToHashMap(myStrings[i]);
    }//else
  }//for
  //
}//func 

void increaseHashMapByOne(String search) {
  // requires that search exists 
  int count = hm.get(search); 
  hm.put(search, count+1);  // increase
}

void addToHashMap(String newWord) {
  hm.put(newWord, 1);  // add to HashMap
}

void showHashMap() {
  // show with text() 
  // Using an enhanced loop to iterate over each entry
  int i=0; 
  for (Map.Entry me : hm.entrySet()) {
    text(me.getKey() + " is ", 33, 30+i*17);
    text(str((int)me.getValue()), 103, 30+i*17);
    i++;
  }
}
//

Here is the project I ended up making. Automatically generated fairy tales from detected objects in mundane images. Built with YOLOv3, XLNet, Processing And Runway

More info here:
https://andreasrefsgaard.dk/project/fairy-tales/

1 Like