It is necessary to fill the map with a word which is repeated and the frequency of occurrence.

String[] str = "<массив слов>"; Map<String,Integer> rez = new LinkedHashMap<String,Integer>(); for(int i = 0;i<str.length;i++){ boolean flag = false; int count =1; // счетчик равен 1 потому что одно слово уже пристутствует for(int j=i+1; j<str.length;j++){ if(str[i].equals(str[j])){ //если слово повторяется счетчик увеличивается на 1; count++; } if(j==str.length-1){ flag=true //Флаг используется для отметки того что цикл по j завершился } } if(count>1&&flag==true){ rez.put(str[i], count); } } } 

result: there is no difference with the situation when the flag is not checked. The need for checking arose in order to mark the end of the inner loop. {you = 2, are = 2, for = 2, job = 2, then = 2, will = 2, to = 2, the = 2, cover = 2, letter = 2, about = 2, and = 2, or = 2, your = 2, should = 2, have = 2, name, = 2, You = 2, which = 2}

  • And what is the question? - Boris Timofeev

1 answer 1

Wow Look at the situation like this: the word is the key. When iterating through the array, check if the following key is in the map:

 rez.containsKey(str); 

If not, insert with a value of 1:

 rez.put(str, 1); 

If there is - replace one more:

 rez.put(str, get(str) + 1); 

Here are two solutions:

 String[] str = new String[]{"<массив слов>"}; Map<String, Integer> rez = new LinkedHashMap<String, Integer>(); for(String item : str){ if(rez.containsKey(item)){ rez.put(item, get(item) + 1); } else { rez.put(item, 1); } } 

or so:

 String[] str = new String[]{"<массив слов>"}; Map<String, Integer> rez = new LinkedHashMap<String, Integer>(); for(String item : str){ rez.put(item, get(item) == null? 1 : get(item) + 1); }