feat: add function to get the total amount a domain has occured

This commit is contained in:
Anthony Berg 2024-10-15 16:21:00 +02:00
parent 74d4189808
commit b4cbd34f6d

View File

@ -1,5 +1,47 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Main { public class Main {
public static void main(String[] args) { public static void main(String[] args) {
System.out.println("Hello world!"); // Get the data from the file
List<String> data = ReadFile.open("test.txt");
// Gets a map with the total occurrences for each domain
Map<String, Integer> domains = getDomainTotal(data);
System.out.println(domains);
}
/**
* Totals up the amount of times an email domain occured in the list.
* @param emails A list of emails
* @return A map of email domains and the total amount of times they occured in the <code>emails</code> parameter
*/
private static Map<String, Integer> getDomainTotal(List<String> emails) {
// Create a map of all email address domains and counting them
Map<String, Integer> domains = new HashMap<>();
for (String email : emails) {
if (!EMail.validate(email)) {
throw new IllegalArgumentException("There was an invalid email in the file!");
}
String domain = EMail.getDomain(email);
// Add email domain to the list
if (!domains.containsKey(domain)) {
// Creates new entry in the map if the domain didn't exist before
domains.put(domain, 1);
} else {
// Updates the map with the new total for the domain
// Gets the old total and adds 1
Integer newTotal = domains.get(domain) + 1;
// Update domain value with new total
domains.replace(domain, newTotal);
}
}
return domains;
} }
} }