Is there a good class that can count the occurrences of specific strings in java? I'd like to keep a list of names and then create unique email addresses for each name. For each occurrence of a last name, I'd like to increment the associated number by one.
Ex: If I have 3 people with the last name Smith, I'd like their address to be smith1@(Address), smith2@(Address), and smith3@(Address). I saw a class "Map" but I can't seem to initialize it correctly. Is there a class that I can use to keep a list of strings and their occurrences?
解决方案
Map would be a viable data structure for this, if you're just looking to count the number of emails with given last names. The key would be a String (the last name), and the value would be an Integer (number of occurrences).
You instantiate it as follows:
Map nameOccurrences = new HashMap();
To add a value to the map:
nameOccurrences.put("Smith", 1);
To check if a name is in the map:
if (nameOccurrences.containsKey("Smith")) { ... }
To get a value from the map:
Integer occurrences = nameOccurrences.get("Smith");
Note that names with different capitalization would be considered different keys. If you need to ignore capitalization, you'd have to do something like make the keys all uppercase before adding them to the Map.