Reputation: 1152
I have a method that reads a txt file and I need it to take each word in the text file, and then iterate them in a sorted order, not removing duplicates. I managed to get it working, but would like to get the code to be more efficient. Can someone give me a hinter, what can I do to make it faster? Something other than an ArrayList? Is there another way to sort other than Collections.sort?
public static void doIt(BufferedReader r, PrintWriter w) throws IOException {
ArrayList<String> p = new ArrayList<String>();
String line;
int n = 0;
while ((line = r.readLine()) != null) {
p.add(line);
n++;
}
Collections.sort(p);
Upvotes: 0
Views: 145
Reputation: 129572
Another option would be to use a TreeMap
that maps words to their frequencies.
TreeMap<String, Integer> words = new TreeMap<>();
while ((line = r.readLine()) != null) {
for (String word : line.split("\\s+")) {
if (words.containsKey(line))
words.put(line, words.get(line) + 1);
else
words.put(line, 1);
}
}
It's difficult if not impossible to tell which option will be more efficient without knowing the details of the file you'll be reading, and ultimately timing both variants.
Having said that, it is likely that using a Map
will be preferable in terms of memory. There's no need to store and have to deal with multiple copies of the same word in your collection, it makes more sense to store just one and have with it an associated frequency.
Upvotes: 3