3

I'm new to Java and is trying to learn the concept of shorthanded if-else statement.

I have came up with the code below. However, the code wouldn't compile and displays an error beside the if-else (i.e. ? : ) statement.

Could someone please tell me why is it not working?

Sorry if my question sounds very silly to some of you. I'm new to Java.

Thanks in advance for any help!

List<String> ls1 = new LinkedList<>(Arrays.asList("hello", "world", "morning", "world"));
Map<String, Integer> msi1 = new LinkedHashMap<>();

for(String s1 : ls1){
    Integer i1 = msi1.get(s1);
    i1 == null ? msi1.put(s1, i1) : msi1.put(s1, i1 + 1));//why can't I use the short if-else statement like this.
}
s.alem
  • 12,579
  • 9
  • 44
  • 72
  • 2
    What error did you receive? – user3437460 Mar 18 '16 at 23:23
  • 2
    You can't use a ternary that doesn't return a result, in this case you're ignoring the `boolean` from `put`. The reason it doesn't work as you expect is simple, if `i1 == null` then `msi1.put(s1, null)` which probably isn't what you want. – Elliott Frisch Mar 18 '16 at 23:24
  • 2
    Let me point you [here](https://stackoverflow.com/questions/35330842/ternary-operator-with-multiple-condtions-in-java-throwing-error) and [here](https://stackoverflow.com/questions/15977031/java-ternary-without-assignment). – Majora320 Mar 18 '16 at 23:25
  • 1
    BTW, you don't need a `LinkedList` in this code - you can just iterate `Arrays.asList("hello", "world" /* etc */)` directly. – Andy Turner Mar 18 '16 at 23:30

2 Answers2

10

The ternary expression

condition ? when-true : when-false

is an expression, not a statement, so can't be used where a statement is required.

You can write this as:

msi1.put(s1, (i1 == null) ? i1 : i1 + 1);

because this is a statement.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • thank you very much! now i understood! will tick as soon as SO allows me. :) –  Mar 18 '16 at 23:29
  • 2
    I don't think the true value is correct - I think it should be `1`, otherwise it just stays at `null` forever. (This was copied from OP's code, though) – Andy Turner Mar 18 '16 at 23:32
0

i'm not sure what you are trying to do, In case if you are trying to identify the number of occurances of a value in a map using its key then this is what you should do

Basically remove the extract ')' towards the end and you should always assign the output of ternary operator.

Integer test = i1 == null ? msi1.put(s1,1) : msi1.put(s1, i1 + 1);
Pshemo
  • 122,468
  • 25
  • 185
  • 269