Get size/length of a value in a HashMap

13,043

Use .values() to get a collection containing all the values of the hash map, and then use Collections.frequency() to count the number of objects in the collection.

return Collections.frequency(map.values(), "red");
Share:
13,043
user1621988
Author by

user1621988

Updated on November 22, 2022

Comments

  • user1621988
    user1621988 over 1 year
    Map<Integer, String> map = new HashMap<Integer, String>();
    

    How do I get the size/length of matching value's at the String?

    example:

    1 , Red 2 , Red 3 , Blue 4 , Blue 5 , Red

    Size of the String of RED = 3

    • Jon Skeet
      Jon Skeet over 11 years
      What do you mean by "second" here? HashMaps are unordered.
    • user1621988
      user1621988 over 11 years
      @ JonSkeet Edited, made a little mistake.
    • Roddy of the Frozen Peas
      Roddy of the Frozen Peas over 11 years
      So you're looking for the frequency of a particular value in the map?
    • user1621988
      user1621988 over 11 years
      Im looking for that amount of RED's in the String Values. and this place 3 times.
    • Denys Séguret
      Denys Séguret over 11 years
      So both answers that aren't mine look correct
  • Denys Séguret
    Denys Séguret over 11 years
    I didn't knew this one... I wonder why they decided to put all those methods which have so little use... Java standard API are less and less simple and canonical...