I need to write an expression without if, because I use the ternary operator

if (dictionary.containsKey(key)) { dictionary.put(key, dictionary.get(key) + 1); } else { dictionary.put(key, 1); } 

I write it this way:

  (dictionary.containsKey(key)) ? (dictionary.put(key, dictionary.get(key) + 1)) : (dictionary.put(key, 1)); 

And it gives the error "Not a statement", what to do?

  • dictionary is LinkedHashMap - denisbaic
  • Probably the expression must be placed in the body of the method. - Nikolay Belyakov
  • one
    dictionary.put(key, dictionary.containsKey(key) ? dictionary.get(key) + 1 : 1); - ArchDemon
  • @ ArchDemon Worked, thanks - denisbaic

1 answer 1

Yes, statement in the ternary operator in java is invalid. Alternatively, you can use the ternary operator inside put:

 dictionary.put(key, dictionary.containsKey(key) ? dictionary.get(key) + 1 : 1)