Issue
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?
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++;
}
Edit:
As mentioned by @Holger in the comments , a simplified for-loop
.
for(String val : list) {
int count = map.merge(val, 1, Integer::sum) - 1;
result[i++] = count > 0 ? val + "(" + count + ")" : val;
}
Answered By - Sayan Bhattacharya
Answer Checked By - Marie Seifert (JavaFixing Admin)