Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to mark and edit duplicate words in list java?

Hi I have this list below

String[] list = {"I","think","she","think","he","think","she","loves"};

I want to produce it like below. So the repeated words get increment.

 ["I","think","she","think(1)","he","think(2)","she(1)","loves"];

I’ve tried to explore this logic but I find it hard to add the increment number to my list, so far I’m only able to detect the repeated words. How can I add the number to the repeated words?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can traverse the array and store each word with their number of occurrences in a Map object. As you traverse through and you find a word which is already present in the map then its simply means its a duplicate word.
EG:

Map<String, Integer> map = new HashMap<>();
String[] result = new String[list.length];
int i = 0;
for (String val : list) {
    int count = map.getOrDefault(val, 0); // if map does not contain the key then the default occurrence is 0     
    result[i] = count > 0 ? val + "(" + count + ")" : val;
    count++;
    map.put(val, count);
    i++;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading