BAEL-2800_Copying_a_HashMap_in_Java
This commit is contained in:
parent
96903671b6
commit
68ffec2c2c
|
@ -43,15 +43,6 @@ public class CopyHashMap {
|
||||||
return copyMap;
|
return copyMap;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static HashMap copyMapAndDivideValuesBy2(HashMap originalMap) {
|
|
||||||
Set<Map.Entry> entries = originalMap.entrySet();
|
|
||||||
HashMap copyMap = (HashMap) entries
|
|
||||||
.stream()
|
|
||||||
.collect(Collectors.toMap(mapEntry -> mapEntry.getKey(), mapEntry -> (int)mapEntry.getValue()/2));
|
|
||||||
|
|
||||||
return copyMap;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static HashMap shallowCopy(HashMap originalMap) {
|
public static HashMap shallowCopy(HashMap originalMap) {
|
||||||
return (HashMap) originalMap.clone();
|
return (HashMap) originalMap.clone();
|
||||||
}
|
}
|
||||||
|
|
|
@ -60,20 +60,6 @@ public class CopyHashMapUnitTest {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenHashMap_whenCopy_thenCopyMapShouldHaveValuesDivideBy2() {
|
|
||||||
|
|
||||||
HashMap<String, Integer> heightMap = new HashMap<>();
|
|
||||||
heightMap.put("emp1", 160);
|
|
||||||
heightMap.put("emp2", 165);
|
|
||||||
heightMap.put("emp3", 163);
|
|
||||||
HashMap heightMapCopy = CopyHashMap.copyMapAndDivideValuesBy2(heightMap);
|
|
||||||
|
|
||||||
assertThat(heightMap).isNotEqualTo(heightMapCopy);
|
|
||||||
|
|
||||||
assertThat(heightMap.get("emp1")/2).isEqualTo(heightMapCopy.get("emp1"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenImmutableMap_whenCopyUsingGuava_thenCopyShouldNotChange() {
|
public void givenImmutableMap_whenCopyUsingGuava_thenCopyShouldNotChange() {
|
||||||
Employee emp1 = new Employee("John");
|
Employee emp1 = new Employee("John");
|
||||||
|
|
Loading…
Reference in New Issue