This question has already been answered:

ArrayList<String> words = new ArrayList<String>(); for (int i = 0; i < 20; i++) words.add(reader.readLine()); 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){ HashMap<String, Integer> result = new HashMap<String, Integer>(); for (String word: list) result.put(word, result.containsKey(word) ? result.get(word) + 1: 1); } 

decipher, please, this line:

 result.put(word, result.containsKey(word) ? result.get(word) + 1: 1); 

Marked as a duplicate by participants Alexey Shimansky , Community Spirit Dec 21 '16 at 12:23 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • You do not know what a ternary operator is? or what is a Map? - Vartlok
  • Ternary operator - read, thanks for the hint - enotdk
  • Or double What does it mean to use? and: in the code? .... to choose - Alexey Shimansky

3 answers 3

 result.put(word , result.containsKey(word) ? result.get(word) + 1: 1); 

here word is your key, and the value that is assigned to it is decoded like this

 if (result.containsKey(word)){ // значение будет result = result.get(word) + 1; else{ result = 1; } 

Such a construction is called a one-line condition.

 result.containsKey(word) ? result.get(word) + 1 : 1 

created by an operator ?

Here is an example:

 условие ? значение1 : значение2 

    This is a ternary operator.

    if result.containsKey(word) = true , then the result is result.get(word) + 1 , in the opposite case 1 .

    • it seems understandable, but what does the first word word in brackets mean? - enotdk
    • you first ArrayList <String> words and there you put the data. Then in for (String word: list) you break this data into separate pieces - ogorank
    • Read http: //developer.alexanderklimov.ru/android/java/hashmap.php - ogorank
    • there about HashMap - ogorank

    result is a dictionary, where the key is word, and the value is the number of such words for the current moment. in line

     result.put(word , result.containsKey(word) ? result.get(word) + 1: 1); 

    we update the value for the word key. If result.containsKey(word) , then we write "already counted number of words" + 1, if there was no such word yet, then we will put one in it. At the end of the cycle, we calculate the number for each word in the list (which is fed to the input of the method).