Reputation:
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.
}
Upvotes: 3
Views: 144
Reputation: 140534
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.
Upvotes: 10
Reputation: 3
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);
Upvotes: 0