0

I am trying to make a simple ternary operation on a hash map:

   hashMap.get(number) == 1   ?
       hashMap.remove(number) :
       hashMap.merge(number, 1, Math::subtractExact);

I am getting a 'Not a statement' error from my IDE. What I don't understand is where this is coming from: both calls to remove and merge sound like statements to me.

Blue_Elephant
  • 154
  • 2
  • 7
  • 4
    Note that the ternary operator is **not** meant as a replacement for any if-else statement. If you do not care about the return values of the remove and merge calls, then using the ternary operator isn't the right way to go. – OH GOD SPIDERS Dec 29 '21 at 11:06
  • 1
    Very related: [Java Ternary without Assignment](https://stackoverflow.com/questions/15977031/java-ternary-without-assignment) – Ivar Dec 29 '21 at 11:19
  • @Ivar this is actually what I was looking for, thanks. – Blue_Elephant Dec 29 '21 at 11:24
  • @tgdavies the question you are linking is about avoiding assignment in a Ternary expression in Java. This question is indirectly asking if and why do we need them. – Blue_Elephant Dec 29 '21 at 11:33
  • 1
    Incidentally I think you can do what you want like this: `m.compute(number, (k, v) -> v == null || v == 1 ? null : v - 1);` – tgdavies Dec 29 '21 at 11:46
  • @Blue_Elephant "This question is indirectly asking if and why do we need them" <- Because that's what the ternary operator was intended and invented for. A short syntax to assign a value depending on a condition. – OH GOD SPIDERS Dec 29 '21 at 12:01

1 Answers1

3

You have to assign the value of the ternary operator to some variable:

Integer value =
    hashMap.get(number) == 1   ?
    hashMap.remove(number) :
    hashMap.merge(number, 1, Math::subtractExact);
Eran
  • 387,369
  • 54
  • 702
  • 768