Easiest Way to Sort a List of Words by Occurance

前端 未结 6 2048
南方客
南方客 2021-01-22 09:12

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 ou

6条回答
  •  猫巷女王i
    2021-01-22 09:56

    public List countOccurences(ArrayList list){
      HashMap hm = new HashMap();
      for (String s:list) {
         Integer i = hm.get(s);
         if (i == null){
          i = 0; 
         } 
         i++;
    
         hm.put(s, i);
      }
    
    
      List mapKeys = new ArrayList(hm.keySet());
      List mapValues = new ArrayList(hm.values());
      HashMap sortedMap = new LinkedHashMap();
      TreeSet sortedSet = new TreeSet(mapValues);
      Object[] sortedArray = sortedSet.toArray();
      int size = sortedArray.length;
      for (int i=0; i(sorted.keyset());
    
    }
    

提交回复
热议问题