[英]How to stop repeated print in java
我正在使用以下代碼從 ArrayList 打印項目:
for(int i2 = 0; i2 < a.size(); i2++)
{
word2 = a.get(i2);
for(int j2 = 0; j2 < a.size(); j2++)
{
if(word2.equals(a.get(j2)))
{
counter++;
}
}
if(counter!=0)
{
System.out.println(word2 + " : " + counter);
}
counter = 0;
}
當我打印時,我不想打印出重復項。 就像現在一樣,它會打印
Alphabet : 3
Alright : 3
Apple : 3
Alphabet : 3
Alright : 3
Apple : 3
Alphabet : 3
Alright : 3
Apple : 3
我只想打印
Alphabet : 3
Alright : 3
Apple : 3
如何使它不打印重復項? 我必須使用 ArrayList 進行分配
另一種選擇,雖然性能不是最好的(盡管它對於您的應用程序來說已經足夠了,並且與您當前的代碼具有相似的性能特征),但是創建一個臨時Set
來保存唯一詞的列表,然后使用Collections.frequency()
來計算原始列表中的出現次數,例如使用您的ArrayList<String> a
:
Set<String> unique = new HashSet<String>(a);
for (String word : unique)
System.out.println(word + " : " + Collections.frequency(a, word));
或者甚至只是:
for (String word : new HashSet<String>(a))
System.out.println(word + " : " + Collections.frequency(a, word));
這里的好處是簡短而清晰的代碼。
如果TreeSet
字母順序打印單詞,可以使用TreeSet
如果LinkedHashSet
第一次出現的順序打印單詞,可以使用LinkedHashSet
。
順便說一句,上面不存儲計數供以后使用,您的原始代碼也不會這樣做。 但是,如果您想這樣做,將結果存儲在地圖中很簡單:
Map<String,Integer> wordCounts = new HashMap<String,Integer>();
for (String word : new HashSet<String>(a))
wordCounts.put(word, Collections.frequency(a, word));
// wordCounts now contains a map of strings -> counts.
使用TreeMap<String, Integer>
跟蹤字數
SortedMap<String, Integer> wordFrequencyMap = new TreeMap<String, Integer>();
for (String str : a) {
if (wordFrequencyMap.containsKey(str)) {
int strFreq = Integer.intValue(wordFrequencyMap.get(str));
strFreq++;
wordFrequencyMap.put(str, new Integer(strFreq));
}
else {
wordFrequencyMap.put(str, new Integer(1));
}
}
for (String word : wordFrequencyMap.keySet()) {
System.out.println(word + " : " + wordFrequencyMap.get(word));
}
這種數據結構不允許重復,它會計算每個單詞的出現次數,只需遍歷列表一次。 由於您使用的是帶有String
鍵的TreeMap
,它會在迭代時按字母順序打印鍵
另一個 Java-8 流替代方案:
這將在collect
步驟創建一個映射:鍵是單詞(因為Function.identity()
返回每個單詞),值是頻率(因為Collectors.counting()
返回每個單詞頻率)。 而forEach
步驟只是打印每個條目"<word>: <word-frequency>"
a.stream().collect(Collectors.groupingBy(
Function.identity(),
Collectors.counting()))
.forEach((word, frequency) -> System.out.println(word+": "+frequency));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.