[英]how to report all tied positions for the last element in the list in JAVA
I have a task to print n frequently used words based on their count values across multiple files. 我的任务是根据多个文件中n个常用单词的计数值来打印它们。 Now the issue is after printing n words, I have to print all the ties at the last position
现在的问题是打印n个单词后,我必须在最后一个位置打印所有领带
for instance if I printed 10 frequently used words based on the highest count and the output comes like this when I use a for loop. 例如,如果我根据最高计数打印了10个常用单词,并且在使用for循环时输出如下。
CODE 码
int listSize = newList.size() >= 10 ? 10 : newList.size();
for (int k = 0; k < listSize; k++) {
Words w = newList.get(k);
System.out.println("Word : " + ++j + " " + w.getWord() + " "
+ w.getCount());
// System.out.println(w.getWord());
}
OUTPUT : 输出:
word 1 : liked 104
word 2 : hello 98
....
....
....
word 10 : picnic 15
now If I encounter words further with the same count that is 15 I have to print them also if I have five words with the same word count 15 I have to print all of them that is all ties for the last position must be reported like this 现在,如果我再遇到数量相同的单词,即15,则我也必须打印它们,如果我有五个单词的数量与15相同,我也必须打印所有单词,所有与最后位置的联系都必须这样报告
**OUTPUT :**
word 11 : camera 15
word 12 : monkey 15
word 13 : carrot 15
word 14 : penguin 15
word 15 : bottle 15
how to implement this case guide me thanks in advance 如何实施这种情况,请事先向我表示感谢
If newList
is sorted by getCount
then the simpliest way to print words with same count
as last printed word is: 如果
newList
按getCount
排序,则打印与最后打印的单词count
相同的单词的最简单方法是:
int k; // init k before the cycle
for (k = 0; k < listSize; k++) {
Words w = newList.get(k);
System.out.println("Word : " + ++j + " " + w.getWord() + " "
+ w.getCount());
// System.out.println(w.getWord());
}
if (k > 0) {
int lastCount = newList.get(k - 1).getCount(); // last printed count
// print words from the k-th
while (k < newList.size()
&& newList.get(k).getCount() == lastCount) {
Words w = newList.get(k);
System.out.println("Word : " + ++j + " " + w.getWord() + " "
+ w.getCount());
++k;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.