1
+ package com.baeldung.modifyMapEntryInPlace
2
+
3
+ import org.junit.jupiter.api.Assertions.assertEquals
4
+ import org.junit.jupiter.api.Test
5
+
6
+ class ModifyMapEntryInPlaceUnitTest {
7
+
8
+ @Test
9
+ fun `modifies mutable map entry using put method` () {
10
+ val map = mutableMapOf (" key1" to " value1" , " key2" to " value2" )
11
+ map.put(" key1" , " new value" )
12
+ assertEquals(" new value" , map[" key1" ])
13
+ }
14
+
15
+ @Test
16
+ fun `modifies mutable map entry using bracket operator` () {
17
+ val map = mutableMapOf (" key1" to " value1" , " key2" to " value2" )
18
+ map[" key1" ] = " new value"
19
+
20
+ assertEquals(" new value" , map[" key1" ])
21
+ }
22
+
23
+ @Test
24
+ fun `modifies mutable map entry using replace method` () {
25
+ val map = mutableMapOf (" key1" to " value1" , " key2" to " value2" )
26
+ map.replace(" key1" , " new value" )
27
+ assertEquals(" new value" , map[" key1" ])
28
+ }
29
+
30
+
31
+ @Test
32
+ fun `modifies mutable map entry using compute method` () {
33
+ val map = mutableMapOf (" key1" to " value1" , " key2" to " value2" )
34
+ map.compute(" key1" ) { _, _ -> " new value" }
35
+ assertEquals(" new value" , map[" key1" ])
36
+ }
37
+
38
+ @Test
39
+ fun `modifies mutable map entry using computeIfPresent method` () {
40
+ val map = mutableMapOf (" key1" to " value1" , " key2" to " value2" )
41
+ map.computeIfPresent(" key1" ) { key, value ->
42
+ if (value == " value1" ) " new value"
43
+ else value
44
+ }
45
+ assertEquals(" new value" , map[" key1" ])
46
+ }
47
+ }
0 commit comments