2017-05-21 63 views
-3

我有數組列表,我想查找java列表中字符串出現次數。找到數組列表中字符串出現的次數

假設數組列表中有

good girl, good boy, very good girl, she is good, unwanted group, unwanted list

我想要得到的每種情況

+1

那你所要的輸出是什麼?你是否希望它成爲一個'HashMap'連接每個字符串與它的出現次數,或者它是一個接受一個字符串並返回一個'int'的函數? – ZeBirdeh

+2

預期產量是多少?每個元素只在該列表中一次 –

+0

某些代碼可以幫助我們找到解決方案。 – steven

回答

1

你的問題的數量也不是很明確的。預期產出到底是什麼?你想計算每個列表的出現次數嗎?

一般而言,您將使用Map s來計數發生次數。像HashMap一樣,它們允許快速訪問。

下面是計算給定文本的所有詞出現次數小片段:

final String input = "word word test word"; 
// Splits at word boundary 
final String[] words = input.split("\\b"); 

final HashMap<String, Integer> wordToCount = new HashMap<>(); 
// Iterate all words 
for (final String word : words) { 
    if (!wordToCount.contains(word)) { 
     // Word seen for the first time 
     wordToCount.put(word, 1); 
    } else { 
     // Word was already seen before, increase the counter 
     final int currentCounter = wordToCount.get(word); 
     wordToCount.put(word, currentCounter + 1); 
    } 
} 

// Output the word occurences 
for (final Entry<String, Integer> entry : wordToCount.entrySet()) { 
    System.out.println("Word: " + entry.getKey() + ", #: " + entry.getValue()); 
} 

這段代碼的輸出將是這樣的:

Word: word, #: 3 
Word: test, #: 1 
相關問題