Count occurrences of strings in Java

♀尐吖头ヾ 提交于 2020-01-04 06:20:30

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/4776229/count-occurrences-of-strings-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!