简体   繁体   中英

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. Now the issue is after printing n words, I have to print all the ties at the last position

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.

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

**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:

    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;
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM