From 6b4bab3d6bba9a9008b4cf68d1d8fdba50d1b3f6 Mon Sep 17 00:00:00 2001 From: HausCook Date: Sun, 8 Nov 2026 21:45:30 +0100 Subject: [PATCH] Tried Hashmaps but i do not like i will do with two Arraylists instead :) --- src/Analyser.java | 30 ++++++++++++++++++++++++++++++ src/Main.java | 13 ++++++++++--- src/TextReader.java | 3 +-- 3 files changed, 41 insertions(+), 5 deletions(-) diff --git a/src/Analyser.java b/src/Analyser.java index 024507a..48ddd29 100644 --- a/src/Analyser.java +++ b/src/Analyser.java @@ -1,2 +1,32 @@ +import java.lang.reflect.Array; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + public class Analyser { + + public static int countElements(ArrayList list) { + return list.size(); + } + + public static HashMap individualWordCount(ArrayList words) { + HashMap individualWordsCount = new HashMap<>(); + + for (String word : words) { + if (individualWordsCount.containsKey(word)) { + int currentCount = individualWordsCount.get(word); + individualWordsCount.put(word, currentCount+1); + } else { + individualWordsCount.put(word,1); + } + } + return individualWordsCount; + } + + + public static ArrayList< Map.Entry< String, Integer > > sortWordsByFrequency(HashMap< String, Integer > wordCounts) { + ArrayList< Map.Entry< String, Integer > > sortedList = new ArrayList<>(wordCounts.entrySet()); + sortedList.sort((a, b) -> b.getValue().compareTo(a.getValue())); + return sortedList; + } } diff --git a/src/Main.java b/src/Main.java index cecc10c..27f1c18 100644 --- a/src/Main.java +++ b/src/Main.java @@ -1,6 +1,13 @@ void main() { - IO.println( - TextReader.linesToWords(TextReader.readFile( - "C:\\Users\\Toni G\\IdeaProjects\\GitPeerGroup\\src\\BeeMovieScript.txt"))); + String filePath = "C:\\Users\\Toni G\\IdeaProjects\\GitPeerGroup\\src\\BeeMovieScript.txt"; + + ArrayList fileLines = TextReader.readFileLines(filePath); + ArrayList fileWords = TextReader.linesToWords(fileLines); + HashMap wordCounts = Analyser.individualWordCount(fileWords); + ArrayList< Map.Entry< String, Integer > > sortedList = Analyser.sortWordsByFrequency(wordCounts); + IO.println(wordCounts); + IO.println(sortedList); + + } \ No newline at end of file diff --git a/src/TextReader.java b/src/TextReader.java index b0b8e33..bec1bd3 100644 --- a/src/TextReader.java +++ b/src/TextReader.java @@ -1,6 +1,5 @@ import java.io.File; import java.io.FileNotFoundException; -import java.lang.reflect.Array; import java.util.Scanner; import java.util.ArrayList; @@ -8,7 +7,7 @@ public class TextReader { Scanner sc = new Scanner(System.in); - public static ArrayList readFile(String filePath) { + public static ArrayList readFileLines(String filePath) { ArrayList lines = new ArrayList<>(); File file = new File (filePath);