Library contents

Groovy Map.computeIfPresent

Decrease a stock balance only when the product is already on the ledger.

A simple example

Map.computeIfPresent

  1. Start with A = 3
  2. Do this Subtract 1 for existing A
  3. Result A = 2
The update reads the old value before storing the calculated one.

Syntax

Groovy syntax
stock.computeIfPresent(item, remapping)
Run these examples in Groovy

Save one example at a time as Lesson.groovy. Use Groovy 4 on JDK 21.

groovy Lesson.groovy

Reduce only the stock that is on the ledger

A storeroom issues one mug and receives a request for an unlisted bowl. The clerk should reduce the mug balance but leave the unlisted product out of the ledger.

Result2
Lesson.groovy
def stock = [Mug: 3]
["Mug", "Bowl"].each { item ->
    stock.computeIfPresent(item) { key, count -> count - 1 }
}
println stock["Mug"]
Output
2

Mug falls from three to two. The unlisted Bowl receives no mapping.

Advertisements

Issue paintbrushes

A class has fourteen brushes under its art-room key. An existing stock record is reduced by the number handed out. What value is written back under the same key?

Given14 brushes − 3 issued
Worked result11

Update a mug count

The café has eight cups on its stock card. An existing stock record is reduced by the number handed out. What value is written back under the same key?

Given8 cups − 2 issued
Worked result6

What to watch for

A key mapped to null is skipped. Returning null from the closure removes an existing entry.

Documentation for Map.computeIfPresent