Unable to update value of a HashMap using ternary operator

I was trying to put values in a HashMap using a ternary operator inside a lambda using forEach function in a List object. But that giving me some error. Like …

This works

for (Long aLong: arr) {         
    if (hashMap.containsKey(i)) {
        hashMap.put(i, hashMap.get(i) + 1);
    } else {
        hashMap.put(i, 1L);
    }
}

This works

for (Long aLong: arr) {
    hashMap.containsKey(i) 
    ? hashMap.put(i, hashMap.get(i) + 1) 
    : hashMap.put(i, 1L);
}

This works too

arr.forEach(i -> {
    if (hashMap.containsKey(i)) {
        hashMap.put(i, hashMap.get(i) + 1);
    } else {
        hashMap.put(i, 1L);
    }
});

But Neither this

arr.forEach(i -> {
    hashMap.containsKey(i) 
    ? hashMap.put(i, hashMap.get(i) + 1) 
    : hashMap.put(i, 1L);
});

Nor this

arr.forEach(i -> hashMap.containsKey(i) 
    ? hashMap.put(i, hashMap.get(i) + 1) 
    : hashMap.put(i, 1L));

works. WhY?

2
Leave a Reply

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

I think it didn’t work because of trying to return something (with isn’t allowed in your code). See Java: Ternary with no return. (For method calling)

In your code better to use

arr.forEach(i -> hashMap.put(i, hashMap.getOrDefault(i, 0L) + 1L));

Jason
Guest

The ternary produces an expression and not a statement expression. So you have to use it as an expression to make its usage valid. For example by assigning the result to a variable or as a method return or parameter. So all but the first code is correct. Of course you could use its result as an expression to make it valid but it looks unclear : for (Long i: arr) { Long result = hashMap.containsKey(i) ? hashMap.put(i, hashMap.get(i) + 1) : hashMap.put(i, 1L); } So that is the correct way : for (Long i : arr) { if (hashMap.containsKey(i))… Read more »