好吧,我有一个带有此值的ArrayList
ACU
ACU
ACU
ACU
ACY
ACY
AER
AER
AER
AGC
我需要获取每个Word的项目数,所以
通常,重复单词的数字是变量 所以另一次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<Word> arrayWords = new ArrayList<Word>();
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)
}
}
假设代码之后我会得到
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<Word> arrayWords = new ArrayList<Word>();
//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);
}
提前致谢。
答案 0 :(得分:3)
迭代OriginalList
并将该字词放在HashMap<String, Integer>
中。如果没有,则以count 1
开头,否则递增。
答案 1 :(得分:2)
对于你想做的事情,这可能有点过头了。您可以更简单地创建一个地图,其中三个字母的字符串作为键,计数作为值。然后迭代你的ArrayList:
Map<String, Integer>wordCount = new HashMap<String, int>();
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);
}
答案 2 :(得分:2)
我认为你要找的答案是common-collections'CollectionUtils.getCardinalityMap()。
JavaDoc:返回一个Map,将给定Collection中的每个唯一元素映射到一个Integer,表示Collection中该元素的出现次数。
所以举例......
List<String> words = new ArrayList();
Map counts = CollectionUtils.getCardinalityMap(words);
答案 3 :(得分:1)
为什么不将循环计数器设置为1?
String word1 = OriginalList.get(i-1).getWord();
String word2 = OriginalList.get(i).getWord();
这样,你永远不会超出界限。