Tried Hashmaps but i do not like i will do with two Arraylists instead :)

mainn
HausCook 2026-11-08 21:45:30 +01:00
parent c7a8d2f24c
commit 6b4bab3d6b
3 changed files with 41 additions and 5 deletions

View File

@ -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<String> list) {
return list.size();
}
public static HashMap<String, Integer> individualWordCount(ArrayList<String> words) {
HashMap<String, Integer> 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;
}
}

View File

@ -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<String> fileLines = TextReader.readFileLines(filePath);
ArrayList<String> fileWords = TextReader.linesToWords(fileLines);
HashMap<String, Integer> wordCounts = Analyser.individualWordCount(fileWords);
ArrayList< Map.Entry< String, Integer > > sortedList = Analyser.sortWordsByFrequency(wordCounts);
IO.println(wordCounts);
IO.println(sortedList);
}

View File

@ -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<String> readFile(String filePath) {
public static ArrayList<String> readFileLines(String filePath) {
ArrayList<String> lines = new ArrayList<>();
File file = new File (filePath);