2

What is the best/easiest way to sort a large list of words (10,000-20,000) by the number of times they occur in the list, in Java. I tried a basic implementation but I get an out of memory runtime error, so I need a more efficient way. What would you suggest?

ArrayList<String> occuringWords = new ArrayList<String>();
    ArrayList<Integer> numberOccur = new ArrayList<Integer>();
    String temp;
    int count;
    for(int i = 0; i < finalWords.size(); i++){
        temp = finalWords.get(i);
        count = 0;
        for(int j = 0; j < finalWords.size(); j++){
            if(temp.equals(finalWords.get(j))){
            count++;
            finalWords.remove(j);
            j--;
            }
        }
        if(numberOccur.size() == 0){
            numberOccur.add(count);
            occuringWords.add(temp);
        }else{
            for(int j = 0; j < numberOccur.size(); j++){
            if(count>numberOccur.get(j)){
                numberOccur.add(j, count);
                occuringWords.add(j, temp);
            }
        }
    }
}

Where finalWords is the list of all of the Strings. I had to store the number of times each word occured in a separate arraylist because I couldn't think of a better way to keep them paired without making each word a separate object.

Bart Kiers
  • 166,582
  • 36
  • 299
  • 288
Kleptine
  • 5,089
  • 16
  • 58
  • 81
  • C# LINQ would have made it a no brainer! see http://stackoverflow.com/questions/454601/how-to-count-duplicates-in-list-with-linq It uses Vlad's algo. though, not hashmap. – Fakrudeen Mar 03 '10 at 06:42

6 Answers6

9

Build a HashMap<String, Integer> mapping words to the number of occurrences. The first time you see a word add it to the map and set the count to 1. Every time thereafter if the word already exists in the map increment the count.

This will be much faster since you will only have to iterate over the list of words once. It's the difference between O(n) and O(n2), which for a large dictionary will be a tremendous difference.

At the end you can then take the list of words and sort them by count. You'll have to take them out of the map and add them to a separate data structure to do this. (Hint: you could use a TreeSet with a custom Comparator which compares words based on their frequency. Or, less elegantly, add them to a List and then sort that list, again with a custom Comparator.)

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • And if you are still running out of memory, try and see if you can give your JVM more RAM. Use the -Xmx and and -Xms options for maximum and initial memory. Just because you get a OutOfMemoryException does not mean you are out of physical memory. – phisch Mar 02 '10 at 20:23
  • @John Kugelman: how do you sort a Map on its value? – SyntaxT3rr0r Mar 02 '10 at 20:25
  • @Wizard: Iterate your Map and add them to a Map with the count as the key. Then iterate the resulting map by key. – Lawrence Dol Mar 02 '10 at 20:31
  • Build a list based on Map.entrySet() and sort it with custom comparator. – Konrad Garus Mar 02 '10 at 20:31
  • @John Kugelamn: lol, you keep modifying your answer making my comment invalid. My point was: your first answer was incomplete because you didn't talk about the sorting part ;) – SyntaxT3rr0r Mar 02 '10 at 20:32
  • @Konrad Garus: or use another data structure altogether, like a Tree-bidir map. But my point was that the first answer was rather "sparse", I suppose it's a SO trick to get upvotes faster than other answers: you start by answering one line, then add another one, then another one etc. – SyntaxT3rr0r Mar 02 '10 at 20:33
  • That's why we get an edit button, so we can improve our answers in response to comments. :-) – John Kugelman Mar 02 '10 at 20:41
  • 1
    Instead of rolling your own code to add to the map you can use google collections multiset (http://google-collections.googlecode.com/svn/trunk/javadoc/index.html?com/google/common/collect/Multiset.html). Then you can just sort it. An example of that is at http://philippeadjiman.com/blog/2010/02/20/a-generic-method-for-sorting-google-collections-multiset-per-entry-count/. – Carnell Mar 02 '10 at 21:40
4

The Multiset is what you are looking from google collections. That data structure is exactly built to support your use cases. All you need to do is populate it with your words. It will maintain the frequency for you

Aravind Yarram
  • 78,777
  • 46
  • 231
  • 327
  • +1 Google collections, although now it's included in Google Guava: http://code.google.com/p/google-collections/ http://code.google.com/p/guava-libraries/ – Luca Molteni Mar 03 '10 at 08:53
2

Why all so complicated? You need basically the following:

  1. Sort the words in-place. The same words will be grouped now.
  2. Go through the array, counting duplicates and store the resulting pairs (word, number of occurrences) in other array
  3. Sort the other array by number of occurrences.

The complexity is O(n log n).

Vlad
  • 35,022
  • 6
  • 77
  • 199
  • Also a good answer. This could be faster or slower than my answer depending on how many duplicates there are. I there are relatively few then this will be better as it will avoid the extra data structure; if there are many then mine will eliminate the duplicates before sorting which will save time. – John Kugelman Mar 02 '10 at 20:48
1

Have you considered using String interning in addition to a hashmap? String interning means all same Strings use the same memory location in order to save memory. Based on an answer Sort a Map<Key, Value> by values (Java) please see below:

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.TreeMap;
public class WordOccurSortExample {

public static void main(String[] args) {
        new  WordOccurSortExample();        
}

public WordOccurSortExample()
{
    ArrayList<String> occuringWords = new ArrayList<String>();
    occuringWords.add("Menios".intern());
    occuringWords.add("Menios".intern());
    occuringWords.add("Menios".intern());
    occuringWords.add("Menios".intern());
    occuringWords.add("Moo".intern());
    occuringWords.add("Moo".intern());
    occuringWords.add("Moo".intern());
    occuringWords.add("Moo".intern());
    occuringWords.add("Moo".intern());
    occuringWords.add("Boo".intern());
    occuringWords.add("Boo".intern());
    occuringWords.add("Boo".intern());

    HashMap<String, Integer> occurances = new HashMap<String, Integer>();

    Iterator<String> it = occuringWords.iterator();
    String word;
    Integer count;
    while(it.hasNext())
    {
        word = it.next();

        if((count = occurances.get(word))==null)
        occurances.put(word, 1);
        else
        occurances.put(word, new Integer(count+1)); 
    }       

    ValueComparator bvc =  new ValueComparator(occurances);
    TreeMap<String,Integer> sorted_map = new TreeMap<String,Integer>(bvc);

    System.out.println("unsorted map: "+occuringWords);
    sorted_map.putAll(occurances);
    System.out.println("results: "+sorted_map);
}


class ValueComparator implements Comparator<String> {

    HashMap<String, Integer> base;
    public ValueComparator(HashMap<String, Integer> base) {
        this.base = base;
    }

    // Note: this comparator imposes orderings that are inconsistent with equals.    
    public int compare(String a, String b) {
        if (base.get(a) >= base.get(b)) {
            return -1;
        } else {
            return 1;
        } // returning 0 would merge keys
    }

}

}

Community
  • 1
  • 1
Menelaos
  • 23,508
  • 18
  • 90
  • 155
0
public List<String> countOccurences(ArrayList<String> list){
  HashMap<String, Integer> hm = new HashMap<String, Integer>();
  for (String s:list) {
     Integer i = hm.get(s);
     if (i == null){
      i = 0; 
     } 
     i++;

     hm.put(s, i);
  }


  List<String> mapKeys = new ArrayList<String>(hm.keySet());
  List<Integer> mapValues = new ArrayList<Integer>(hm.values());
  HashMap<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
  TreeSet<Integer> sortedSet = new TreeSet<Integer>(mapValues);
  Object[] sortedArray = sortedSet.toArray();
  int size = sortedArray.length;
  for (int i=0; i<size; i++){
     sortedMap.put(mapKeys.get(mapValues.indexOf(sortedArray[i])), 
                  (Double)sortedArray[i]);
  }
  return new ArrayList<String>(sorted.keyset());

}
Paul
  • 4,812
  • 3
  • 27
  • 38
-2

THe easiest way to sort your words is alphabetically. But you can also do it by how many letters that word has that exist in another word.