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;