int values=1;
HashMap<String, Integer> result = new HashMap<String, Integer>();
for (int unique = 0; unique <list.size(); unique++) {
//verifies if the sort list has another unique word
if(unique ==list.size()-1&&list.get(unique).equals(list.get(unique - 1))|| unique <list.size()-1&&list.get(unique).equals(list.get(unique + 1))){
//if it is at the last possible position add key and value to result
if(unique ==list.size()-1)
result.put(list.get(unique), values);
values++;
}
//verifies if the last word and actual word are different
else if(unique ==list.size()-1&&!list.get(unique).equals(list.get(unique - 1))|| unique <list.size()-1&&!list.get(unique).equals(list.get(unique + 1))){
//if they are different and value is greather than 1... return result of the last unique word and value
if(values!=1){
result.put(list.get(unique), values);
}//reset value
values=1;
}
}
return result;
package com.codegym.task.task10.task1016;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/*
Identical words in a list
*/
public class Solution {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
ArrayList<String> words = new ArrayList<String>();
for (int i = 0; i < 20; i++) {
words.add(reader.readLine());
}
//
words.sort(null);
Map<String, Integer> map = countWords(words);
for (Map.Entry<String, Integer> pair : map.entrySet()) {
System.out.println(pair.getKey() + " " + pair.getValue());
}
}
public static Map<String, Integer> countWords(ArrayList<String> list) {
int values=1;
HashMap<String, Integer> result = new HashMap<String, Integer>();
for (int unique = 0; unique <list.size(); unique++) {
//verifies if the sort list has another unique word
if(unique ==list.size()-1&&list.get(unique).equals(list.get(unique - 1))|| unique <list.size()-1&&list.get(unique).equals(list.get(unique + 1))){
//if it is at the last possible position add key and value to result
if(unique ==list.size()-1)
result.put(list.get(unique), values);
values++;
}
//verifies if the last word and actual word are different
else if(unique ==list.size()-1&&!list.get(unique).equals(list.get(unique - 1))|| unique <list.size()-1&&!list.get(unique).equals(list.get(unique + 1))){
//if they are different and value is greather than 1... return result of the last unique word and value
if(values!=1){
result.put(list.get(unique), values);
}//reset value
values=1;
}
}
return result;
}
}