简体   繁体   中英

How can I make my sorted list be more efficient?

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM