问题:在Arraylist中统计字段并保存

12 浏览
0 Comments

问题:在Arraylist中统计字段并保存

好的,我有一个包含以下值的ArrayList

ACU
ACU
ACU
ACU
ACY
ACY
AER
AER
AER
AGC

我需要获取每个单词的项数,所以对于

  • ACU,我们会得到4个项,
  • ACY,我们会得到2个项,
  • AER,我们将得到3个项,
  • AGC,我们将得到1个项。

一般来说,单词重复的次数是一个变量,所以ACU下一次可能是1,ACY下一次可能是100..

那么,我有一个类用于保留“whatWord”和“howMany”值

public class Word {
private String whatWord;
private int howMany;
public  cVOPlaza(String whatWord, int  howMany){
  this.whatWord = whatWord;
  this.howMany= howMany;     
}
public String getwhatWord() {
  return whatWord;
}
public void setwhatWord(String whatWord) {
   this.whatWord = whatWord;
}
public int gethowMany() {
   return howMany;
 }
public void sethowMany(int howMany) {
   this.howMany = howMany;
 } 
}

我在这里卡住了,因为我知道下面代码中的get(i+1)部分会导致错误,你知道值不存在,但是我不知道该怎么办...

ArrayList arrayWords = new ArrayList();
 int cuantos = 0;
     for (int i=0;i<OriginalList.size();i++) {
     String word1  = OriginalList.get(i).getWord();
     String word2 = OriginalList.get(i+1).getWord();
             if (word1.equals(word2)){
                       //this counter is bad here... 
                       //where do i increment it??
         howMany++;
         Word a = new Word(word1,howMany);
         ///....DONT KNOW WHERE TO ADD THE OBJECT 
                        //to the list
                         //arrayWords.add(a)
      }
        }

假设在for代码后,我将得到

ACU 4,
ACY 2,
AER 3,
AGC 1.

首先我尝试做一个HashMap尝试,请帮助我完成这段代码:

 HashMap table = new HashMap();
    int value=0;
    String key=null;
   //INITIALIZE HASH??? LIKE THIS
    for (int i = 0; i < OriginalList.size; i++) {
        table.put(0,OriginalList.get(i).getWord());      
    }
         String word1=null;
         ArrayList arrayWords = new ArrayList();
         //LOOP FOR SEARCHING
         for (int i = 0; i < OriginalList.size(); i++) {
               key = OriginalList.get(i).getWord();
               if (table.containsKey(key)) { 
                       word1 = (String) table.get(key);
                       value++;
               }else {
                      word1 = (String) table.get(key);
                      value=1
               }
             //Add result??
             Word a = new Word(word1,value);
         }

非常感谢。

admin 更改状态以发布 2023年5月21日
0
0 Comments

这可能对于你想要做的事情来说有些过度了。你可以更简单地创建一个以三个字母字符串为键,计数为值的映射。然后只需迭代你的ArrayList:

MapwordCount = new HashMap();
for(String seq : yourWordList){
    // increment the count of the word by first obtaining its count,
    // and then incrementing it. Paranthesis for clarity
    wordCount.put(seq, (wordCount.get(seq)) + 1);
}

0
0 Comments

遍历OriginalList,并将该单词添加到一个 HashMap中。如果该单词不存在,则从计数1开始;否则将其计数加1。

0