0

I have a HashMap variable called map were the key is an Integer and the value is a String.

Say for example that there are 100 values in map. I want to search the 100 values for "Donkey" and then I want to return an Integer with the number of "Donkey" in map if there are none then return Integer 0. I tried to use a for loop with map.values() but no luck.

Can someone give me a hint please?

1
  • If you want a count, with 0 for not found, why use a boxed Integer object as the result, and not regular int value? Commented Apr 20, 2016 at 23:15

2 Answers 2

4

Try this:

int count = Collections.frequency(mapVar.values(), "Donkey");
System.out.println(count);

Let me know whether its worked :)

Sign up to request clarification or add additional context in comments.

3 Comments

Perfect, though to be a stickler, that's an int value and OP wants an Integer, and variable is called map, not mapVar. ;-)
Yea i know :) Sorry about that!
Thank you for your answer, this works great for single word values. But for long strings it will not work. For example if values look something like this [1="This donkey is a horse"], [2="My friend is a donkey"]. I know I did not express my question correctly.
0

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}

5 Comments

Thanks for your answer but it is not what I need now. I might use this in a different project though.
@Maximilian, from your other post, you want to find "donkey" in "This donkey is a horse". In the countAnimal method, change val.equals(animal) to val.toUpperCase().contains(animal.toUpperCase()). This approach would handle a sentence approach. However, if you also need "A donkey is a donkey is a donkey" to return 3 (rather than whether a given sentence contains the animal at all), split the String by spaces, and pass to the countAnimal method.
I tried your code and initially it worked with the map values that you gave as example. However, I am trying to apply this to my program and its not returning anything. My program is using the twitter API and I put tweets gathered in a HashMap called textMap. I don't know if you have experience with the twitter API, but if you do and willing to help me I will put my entire code here for you to see.
@Maximilian, I know nothing about Twitter's API. Assuming the Map is defined as you suggested in the original question (i.e., Map<Integer,String>), where the String value is a sentence, there is no reason to suspect the code would not work. I would add debugging statements to check expected values, especially the value of each String in the map.values(). After a bit more investigation, I would suggest taking your next efforts and posting a new question, as it is not possible to debug in the comments.
Thanks for your reply, I got it working, but it took a little struggle.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.