The Collections.frequency approach is a nice one. However, the assertion that the map.values() didn't work is a bit strange, as it should work. I would add it is especially strange since the Collection passed to the Collections.frequency is the map.values().
// method to do the counting of a particular animal in a map
static Integer countAnimal(String animal, Map<Integer, String> map)
{
int cnt = 0;
for (String val : map.values()) {
if (val.equals(animal)) {
++cnt;
}
}
return new Integer(cnt);
}
public static void main(String[] args)
{
String[] animals = new String[] { "cat", "dog", "pig", "goat", "donkey", "horse", "cow" };
Map<Integer, String> map = new HashMap<>();
// load map for test
Random rnd = new Random();
for (int i = 0; i < 100; ++i) {
String animal = animals[rnd.nextInt(animals.length)];
map.put(new Integer(i), animal);
}
// count how many there are
Map<String, Integer> numAnimals = new HashMap<>();
for (String animal : animals) {
numAnimals.put(animal, countAnimal(animal, map));
}
System.out.println(numAnimals);
// show the cool Collections.frequency approach
Integer count = Collections.frequency(map.values(), "dog");
System.out.println("dog: " + count);
}
Example output:
{horse=18, cat=13, donkey=23, cow=15, goat=17, dog=3, pig=11}
dog: 3
EDIT: an update that allows splitting a string to find the count. Basically countAnimal will split the String retrieved from the map, and then check each token to see if it is an animal. Changed the test case slightly as well. It works based upon the updated comment. It does not consider, however, plurals. The trivial case of "cat" and "cats" is easily handled, but "mouse" and "mice" would be more difficult, and require additional work.
public static void main(String[] args)
{
String[] animals = new String[] { "cat", "dog", "pig", "goat",
"donkey", "horse", "cow" };
Map<Integer, String> map = new HashMap<>();
// load map for test
map.put(1, "My friend has a horse");
map.put(2, "A bear can be big"); // will not be found
map.put(3, "A cat is a loner");
map.put(4, "A dog is man's best friend");
map.put(5, "The cat and the dog are peacefully sleeping");
// count how many there are
Map<String, Integer> numAnimals = new HashMap<>();
for (String animal : animals) {
numAnimals.put(animal, countAnimal(animal, map));
}
System.out.println(numAnimals);
}
static Integer countAnimal(String animal, Map<Integer, String> map)
{
int cnt = 0;
for (String val : map.values()) {
// split the val by space
String[] tokens = val.split("[\\s]+");
for (String token : tokens) {
if (token.equalsIgnoreCase(animal)) {
++cnt;
}
}
}
return new Integer(cnt);
}
Example output:
{horse=1, cat=2, donkey=0, cow=0, goat=0, dog=2, pig=0}
0for not found, why use a boxedIntegerobject as the result, and not regularintvalue?