BAEL-1438: TreeMap vs HashMap (#3265)

* BAEL-1438: Final code.

* BAEL-1438: Temporary commit.

* BAEL-1438: New Changes.

* BAEL-1438: New test case to support Java 8 features.
This commit is contained in:
Shouvik Bhattacharya 2017-12-21 22:14:27 +05:30 committed by maibin
parent 2bff7a623e
commit d14cc42306
2 changed files with 75 additions and 0 deletions

View File

@ -0,0 +1,60 @@
package com.baeldung.collection;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;
public class WhenComparingTreeMapVsHashMap {
@Test
public void whenInsertObjectsTreeMap_thenNaturalOrder() {
Map<Integer, String> treemap = new TreeMap<>();
treemap.put(3, "TreeMap");
treemap.put(2, "vs");
treemap.put(1, "HashMap");
Assert.assertThat(treemap.keySet(), Matchers.contains(1, 2, 3));
}
@Test(expected = NullPointerException.class)
public void whenInsertNullInTreeMap_thenException() {
Map<Integer, String> treemap = new TreeMap<>();
treemap.put(null, "NullPointerException");
}
@Test
public void whenInsertObjectsHashMap_thenRandomOrder() {
Map<Integer, String> hashmap = new HashMap<>();
hashmap.put(3, "TreeMap");
hashmap.put(2, "vs");
hashmap.put(1, "HashMap");
Assert.assertThat(hashmap.keySet(), Matchers.containsInAnyOrder(1, 2, 3));
}
@Test
public void whenInsertNullInHashMap_thenInsertsNull() {
Map<Integer, String> hashmap = new HashMap<>();
hashmap.put(null, null);
Assert.assertNull(hashmap.get(null));
}
@Test
public void givenHashMapAndTreeMap_whenputDuplicates_thenOnlyUnique() {
Map<Integer, String> treeMap = new HashMap<>();
treeMap.put(1, "Baeldung");
treeMap.put(1, "Baeldung");
Assert.assertTrue(treeMap.size() == 1);
Map<Integer, String> treeMap2 = new TreeMap<>();
treeMap2.put(1, "Baeldung");
treeMap2.put(1, "Baeldung");
Assert.assertTrue(treeMap2.size() == 1);
}
}

View File

@ -3,7 +3,12 @@ package com.baeldung;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
public class ExceptionUnitTest {
@ -22,4 +27,14 @@ public class ExceptionUnitTest {
Integer.valueOf(str);
});
}
@Test
public void whenModifyMapDuringIteration_thenThrowExecption() {
Map<Integer, String> hashmap = new HashMap<>();
hashmap.put(1, "One");
hashmap.put(2, "Two");
Executable executable = () -> hashmap.forEach((key, value) -> hashmap.remove(1));
assertThrows(ConcurrentModificationException.class, executable);
}
}