From b4cbd34f6d83dc8231c568ee8f6e1f5e821249f9 Mon Sep 17 00:00:00 2001 From: Anthony Berg Date: Tue, 15 Oct 2024 16:21:00 +0200 Subject: [PATCH] feat: add function to get the total amount a domain has occured --- src/Main.java | 44 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/src/Main.java b/src/Main.java index 3b09b25..4dd9fed 100644 --- a/src/Main.java +++ b/src/Main.java @@ -1,5 +1,47 @@ +import java.util.HashMap; +import java.util.List; +import java.util.Map; + public class Main { public static void main(String[] args) { - System.out.println("Hello world!"); + // Get the data from the file + List data = ReadFile.open("test.txt"); + + // Gets a map with the total occurrences for each domain + Map 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 emails parameter + */ + private static Map getDomainTotal(List emails) { + // Create a map of all email address domains and counting them + Map 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; } } \ No newline at end of file