Skip to content

Commit bf98150

Browse files
committed
computeIfPresent on multimap example
1 parent 426da70 commit bf98150

File tree

1 file changed

+26
-2
lines changed

1 file changed

+26
-2
lines changed

src/test/java/MapModifyingTest.java

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,7 @@
66
import static org.hamcrest.CoreMatchers.is;
77
import static org.hamcrest.CoreMatchers.nullValue;
88
import static org.hamcrest.MatcherAssert.assertThat;
9-
import static org.junit.Assert.assertNull;
10-
import static org.junit.Assert.assertTrue;
9+
import static org.junit.Assert.*;
1110

1211
/**
1312
* Created by mtumilowicz on 2018-11-09.
@@ -215,6 +214,31 @@ public void computeIfPresent_absent() {
215214

216215
assertTrue(map.isEmpty());
217216
}
217+
218+
@Test
219+
public void computeIfPresent_multimap() {
220+
Map<Integer, Set<Integer>> map = new HashMap<>();
221+
222+
map.computeIfAbsent(1, x -> new HashSet<>()).add(1);
223+
map.get(1).add(2);
224+
map.get(1).add(3);
225+
map.get(1).add(4);
226+
227+
map.computeIfPresent(1 , (key, set) -> set.remove(4) && set.isEmpty() ? null : set);
228+
229+
assertThat(map.get(1), is(new HashSet<>(Arrays.asList(1, 2, 3))));
230+
}
231+
232+
@Test
233+
public void computeIfPresent_multimap_removeEntry() {
234+
Map<Integer, Set<Integer>> map = new HashMap<>();
235+
236+
map.computeIfAbsent(1, x -> new HashSet<>()).add(1);
237+
238+
map.computeIfPresent(1 , (key, set) -> set.remove(1) && set.isEmpty() ? null : set);
239+
240+
assertFalse(map.containsKey(1));
241+
}
218242

219243
@Test
220244
public void compute_present_nonNullValue() {

0 commit comments

Comments
 (0)