Count occurrences of strings in Java

2019-07-13 06:49发布

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?

2条回答
贪生不怕死
2楼-- · 2019-07-13 07:23

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<String, Integer> nameOccurrences = new HashMap<String, Integer>();

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.

查看更多
做个烂人
3楼-- · 2019-07-13 07:37

Bag is the data structure you are looking for. Multiset is a Bag implementation from google-guava library.

查看更多
登录 后发表回答