JAVA-1188: Moved modules to core-java-modules

This commit is contained in:
sampadawagde
2020-04-07 14:50:03 +05:30
parent a3d01425f7
commit b0add81c74
39 changed files with 2959 additions and 0 deletions

View File

@@ -0,0 +1,16 @@
## Java Collections Cookbooks and Examples
This module contains articles about Map data structures in Java.
### Relevant Articles:
- [Guide to the Guava BiMap](https://www.baeldung.com/guava-bimap)
- [A Guide to Java HashMap](https://www.baeldung.com/java-hashmap)
- [A Guide to LinkedHashMap in Java](https://www.baeldung.com/java-linked-hashmap)
- [A Guide to TreeMap in Java](https://www.baeldung.com/java-treemap)
- [How to Store Duplicate Keys in a Map in Java?](https://www.baeldung.com/java-map-duplicate-keys)
- [Get the Key for a Value from a Java Map](https://www.baeldung.com/java-map-key-from-value)
- [How to Check If a Key Exists in a Map](https://www.baeldung.com/java-map-key-exists)
- [Immutable Map Implementations in Java](https://www.baeldung.com/java-immutable-maps)
- [Guide to Apache Commons MultiValuedMap](https://www.baeldung.com/apache-commons-multi-valued-map)
- [The Java HashMap Under the Hood](https://www.baeldung.com/java-hashmap-advanced)
- More articles: [[next -->]](/core-java-collections-maps-2)

View File

@@ -0,0 +1,35 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-collections-maps</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-collections-maps</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<commons-collections4.version>4.1</commons-collections4.version>
<assertj.version>3.6.1</assertj.version>
</properties>
</project>

View File

@@ -0,0 +1,44 @@
/**
*
*/
package com.baeldung.map;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Stream;
/**
* @author swpraman
*
*/
public class MapUtil {
public static <K, V> Stream<K> keys(Map<K, V> map, V value) {
return map.entrySet()
.stream()
.filter(entry -> value.equals(entry.getValue()))
.map(Map.Entry::getKey);
}
public static <K, V> Set<K> getKeys(Map<K, V> map, V value) {
Set<K> keys = new HashSet<>();
for (Entry<K, V> entry : map.entrySet()) {
if (entry.getValue().equals(value)) {
keys.add(entry.getKey());
}
}
return keys;
}
public static <K, V> K getKey(Map<K, V> map, V value) {
for (Entry<K, V> entry : map.entrySet()) {
if (entry.getValue().equals(value)) {
return entry.getKey();
}
}
return null;
}
}

View File

@@ -0,0 +1,64 @@
package com.baeldung.map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MyKey {
private static final Logger LOG = LoggerFactory.getLogger(MyKey.class);
private String name;
private int id;
public MyKey(int id, String name) {
this.id = id;
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public int hashCode() {
LOG.debug("Calling hashCode()");
return id;
}
@Override
public String toString() {
return "MyKey [name=" + name + ", id=" + id + "]";
}
@Override
public boolean equals(Object obj) {
LOG.debug("Calling equals() for key: " + obj);
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MyKey other = (MyKey) obj;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}

View File

@@ -0,0 +1,23 @@
package com.baeldung.map;
import java.util.LinkedHashMap;
import java.util.Map;
public class MyLinkedHashMap<K, V> extends LinkedHashMap<K, V> {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final int MAX_ENTRIES = 5;
public MyLinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder) {
super(initialCapacity, loadFactor, accessOrder);
}
@Override
protected boolean removeEldestEntry(Map.Entry eldest) {
return size() > MAX_ENTRIES;
}
}

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@@ -0,0 +1,120 @@
package com.baeldung.guava;
import static org.junit.Assert.*;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import com.google.common.collect.BiMap;
import com.google.common.collect.EnumHashBiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.ImmutableBiMap;
public class GuavaBiMapUnitTest {
@Test
public void whenQueryByValue_returnsKey() {
final BiMap<String, String> capitalCountryBiMap = HashBiMap.create();
capitalCountryBiMap.put("New Delhi", "India");
capitalCountryBiMap.put("Washingon, D.C.", "USA");
capitalCountryBiMap.put("Moscow", "Russia");
final String countryCapitalName = capitalCountryBiMap.inverse().get("India");
assertEquals("New Delhi", countryCapitalName);
}
@Test
public void whenCreateBiMapFromExistingMap_returnsKey() {
final Map<String, String> capitalCountryMap = new HashMap<>();
capitalCountryMap.put("New Delhi", "India");
capitalCountryMap.put("Washingon, D.C.", "USA");
capitalCountryMap.put("Moscow", "Russia");
final BiMap<String, String> capitalCountryBiMap = HashBiMap.create(capitalCountryMap);
final String countryCapitalName = capitalCountryBiMap.inverse().get("India");
assertEquals("New Delhi", countryCapitalName);
}
@Test
public void whenQueryByKey_returnsValue() {
final BiMap<String, String> capitalCountryBiMap = HashBiMap.create();
capitalCountryBiMap.put("New Delhi", "India");
capitalCountryBiMap.put("Washingon, D.C.", "USA");
capitalCountryBiMap.put("Moscow", "Russia");
assertEquals("USA", capitalCountryBiMap.get("Washingon, D.C."));
}
@Test(expected = IllegalArgumentException.class)
public void whenSameValueIsPresent_throwsException() {
final BiMap<String, String> capitalCountryBiMap = HashBiMap.create();
capitalCountryBiMap.put("New Delhi", "India");
capitalCountryBiMap.put("Washingon, D.C.", "USA");
capitalCountryBiMap.put("Moscow", "Russia");
capitalCountryBiMap.put("Trump", "USA");
}
@Test
public void givenSameValueIsPresent_whenForcePut_completesSuccessfully() {
final BiMap<String, String> capitalCountryBiMap = HashBiMap.create();
capitalCountryBiMap.put("New Delhi", "India");
capitalCountryBiMap.put("Washingon, D.C.", "USA");
capitalCountryBiMap.put("Moscow", "Russia");
capitalCountryBiMap.forcePut("Trump", "USA");
assertEquals("USA", capitalCountryBiMap.get("Trump"));
assertEquals("Trump", capitalCountryBiMap.inverse().get("USA"));
}
@Test
public void whenSameKeyIsPresent_replacesAlreadyPresent() {
final BiMap<String, String> capitalCountryBiMap = HashBiMap.create();
capitalCountryBiMap.put("New Delhi", "India");
capitalCountryBiMap.put("Washingon, D.C.", "USA");
capitalCountryBiMap.put("Moscow", "Russia");
capitalCountryBiMap.put("Washingon, D.C.", "HongKong");
assertEquals("HongKong", capitalCountryBiMap.get("Washingon, D.C."));
}
@Test
public void whenUsingImmutableBiMap_allowsPutSuccessfully() {
final BiMap<String, String> capitalCountryBiMap = new ImmutableBiMap.Builder<String, String>().put("New Delhi", "India").put("Washingon, D.C.", "USA").put("Moscow", "Russia").build();
assertEquals("USA", capitalCountryBiMap.get("Washingon, D.C."));
}
@Test(expected = UnsupportedOperationException.class)
public void whenUsingImmutableBiMap_doesntAllowRemove() {
final BiMap<String, String> capitalCountryBiMap = new ImmutableBiMap.Builder<String, String>().put("New Delhi", "India").put("Washingon, D.C.", "USA").put("Moscow", "Russia").build();
capitalCountryBiMap.remove("New Delhi");
}
@Test(expected = UnsupportedOperationException.class)
public void whenUsingImmutableBiMap_doesntAllowPut() {
final BiMap<String, String> capitalCountryBiMap = new ImmutableBiMap.Builder<String, String>().put("New Delhi", "India").put("Washingon, D.C.", "USA").put("Moscow", "Russia").build();
capitalCountryBiMap.put("New York", "USA");
}
private enum Operation {
ADD, SUBTRACT, MULTIPLY, DIVIDE
}
@Test
public void whenUsingEnumAsKeyInMap_replacesAlreadyPresent() {
final BiMap<Operation, String> operationStringBiMap = EnumHashBiMap.create(Operation.class);
operationStringBiMap.put(Operation.ADD, "Add");
operationStringBiMap.put(Operation.SUBTRACT, "Subtract");
operationStringBiMap.put(Operation.MULTIPLY, "Multiply");
operationStringBiMap.put(Operation.DIVIDE, "Divide");
assertEquals("Divide", operationStringBiMap.get(Operation.DIVIDE));
}
}

View File

@@ -0,0 +1,84 @@
package com.baeldung.map;
import com.google.common.collect.ImmutableMap;
import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
public class ImmutableMapUnitTest {
@Test
public void whenCollectionsUnModifiableMapMethod_thenOriginalCollectionChangesReflectInUnmodifiableMap() {
Map<String, String> mutableMap = new HashMap<>();
mutableMap.put("USA", "North America");
Map<String, String> unmodifiableMap = Collections.unmodifiableMap(mutableMap);
assertThrows(UnsupportedOperationException.class, () -> unmodifiableMap.put("Canada", "North America"));
mutableMap.remove("USA");
assertFalse(unmodifiableMap.containsKey("USA"));
mutableMap.put("Mexico", "North America");
assertTrue(unmodifiableMap.containsKey("Mexico"));
}
@Test
@SuppressWarnings("deprecation")
public void whenGuavaImmutableMapFromCopyOfMethod_thenOriginalCollectionChangesDoNotReflectInImmutableMap() {
Map<String, String> mutableMap = new HashMap<>();
mutableMap.put("USA", "North America");
ImmutableMap<String, String> immutableMap = ImmutableMap.copyOf(mutableMap);
assertTrue(immutableMap.containsKey("USA"));
assertThrows(UnsupportedOperationException.class, () -> immutableMap.put("Canada", "North America"));
mutableMap.remove("USA");
assertTrue(immutableMap.containsKey("USA"));
mutableMap.put("Mexico", "North America");
assertFalse(immutableMap.containsKey("Mexico"));
}
@Test
@SuppressWarnings("deprecation")
public void whenGuavaImmutableMapFromBuilderMethod_thenOriginalCollectionChangesDoNotReflectInImmutableMap() {
Map<String, String> mutableMap = new HashMap<>();
mutableMap.put("USA", "North America");
ImmutableMap<String, String> immutableMap = ImmutableMap.<String, String>builder()
.putAll(mutableMap)
.put("Costa Rica", "North America")
.build();
assertTrue(immutableMap.containsKey("USA"));
assertTrue(immutableMap.containsKey("Costa Rica"));
assertThrows(UnsupportedOperationException.class, () -> immutableMap.put("Canada", "North America"));
mutableMap.remove("USA");
assertTrue(immutableMap.containsKey("USA"));
mutableMap.put("Mexico", "North America");
assertFalse(immutableMap.containsKey("Mexico"));
}
@Test
@SuppressWarnings("deprecation")
public void whenGuavaImmutableMapFromOfMethod_thenOriginalCollectionChangesDoNotReflectInImmutableMap() {
ImmutableMap<String, String> immutableMap = ImmutableMap.of("USA", "North America", "Costa Rica", "North America");
assertTrue(immutableMap.containsKey("USA"));
assertTrue(immutableMap.containsKey("Costa Rica"));
assertThrows(UnsupportedOperationException.class, () -> immutableMap.put("Canada", "North America"));
}
}

View File

@@ -0,0 +1,27 @@
package com.baeldung.map;
import org.junit.Test;
import java.util.Collections;
import java.util.Map;
import static org.junit.Assert.*;
public class KeyCheckUnitTest {
@Test
public void whenKeyIsPresent_thenContainsKeyReturnsTrue() {
Map<String, String> map = Collections.singletonMap("key", "value");
assertTrue(map.containsKey("key"));
assertFalse(map.containsKey("missing"));
}
@Test
public void whenKeyHasNullValue_thenGetStillWorks() {
Map<String, String> map = Collections.singletonMap("nothing", null);
assertTrue(map.containsKey("nothing"));
assertNull(map.get("nothing"));
}
}

View File

@@ -0,0 +1,119 @@
package com.baeldung.map;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.TreeMultimap;
import org.apache.commons.collections4.MultiMap;
import org.apache.commons.collections4.MultiMapUtils;
import org.apache.commons.collections4.MultiValuedMap;
import org.apache.commons.collections4.map.MultiValueMap;
import org.apache.commons.collections4.multimap.ArrayListValuedHashMap;
import org.apache.commons.collections4.multimap.HashSetValuedHashMap;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import static org.assertj.core.api.Assertions.assertThat;
public class MapMultipleValuesUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(MapMultipleValuesUnitTest.class);
@Test
public void givenHashMap_whenPuttingTwice_thenReturningFirstValue() {
Map<String, String> map = new HashMap<>();
assertThat(map.put("key1", "value1")).isEqualTo(null);
assertThat(map.put("key1", "value2")).isEqualTo("value1");
assertThat(map.get("key1")).isEqualTo("value2");
}
@Test
public void givenCollectionAsValue_whenPuttingTwice_thenReturningCollection() {
Map<String, List<String>> map = new HashMap<>();
List<String> list = new ArrayList<>();
map.put("key1", list);
map.get("key1").add("value1");
map.get("key1").add("value2");
assertThat(map.get("key1").get(0)).isEqualTo("value1");
assertThat(map.get("key1").get(1)).isEqualTo("value2");
}
@Test
public void givenCollectionAsValueAndJava8_whenPuttingTwice_thenReturningCollection() {
Map<String, List<String>> map = new HashMap<>();
map.computeIfAbsent("key1", k -> new ArrayList<>()).add("value1");
map.computeIfAbsent("key1", k -> new ArrayList<>()).add("value2");
assertThat(map.get("key1").get(0)).isEqualTo("value1");
assertThat(map.get("key1").get(1)).isEqualTo("value2");
}
@Test
public void givenMultiValueMap_whenPuttingTwice_thenReturningValues() {
MultiMap<String, String> map = new MultiValueMap<>();
map.put("key1", "value1");
map.put("key1", "value2");
assertThat((Collection<String>) map.get("key1"))
.contains("value1", "value2");
}
@Test
public void givenArrayListValuedHashMap_whenPuttingDoubleValues_thenReturningAllValues() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("key1", "value1");
map.put("key1", "value2");
map.put("key1", "value2");
assertThat((Collection<String>) map.get("key1"))
.containsExactly("value1", "value2", "value2");
}
@Test
public void givenHashSetValuedHashMap_whenPuttingTwiceTheSame_thenReturningOneValue() {
MultiValuedMap<String, String> map = new HashSetValuedHashMap<>();
map.put("key1", "value1");
map.put("key1", "value1");
assertThat((Collection<String>) map.get("key1"))
.containsExactly("value1");
}
@Test(expected = UnsupportedOperationException.class)
public void givenUnmodifiableMultiValuedMap_whenInserting_thenThrowingException() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("key1", "value1");
map.put("key1", "value2");
MultiValuedMap<String, String> immutableMap =
MultiMapUtils.unmodifiableMultiValuedMap(map);
immutableMap.put("key1", "value3");
}
@Test
public void givenArrayListMultiMap_whenInserting_thenCorrectOutput() {
Multimap<String, String> map = ArrayListMultimap.create();
map.put("key1", "value2");
map.put("key1", "value1");
assertThat((Collection<String>) map.get("key1"))
.containsExactly("value2", "value1");
}
@Test
public void givenLinkedHashMultiMap_whenInserting_thenReturningValuesInInsertionOrder() {
Multimap<String, String> map = LinkedHashMultimap.create();
map.put("key1", "value3");
map.put("key1", "value1");
map.put("key1", "value2");
assertThat((Collection<String>) map.get("key1"))
.containsExactly("value3", "value1", "value2");
}
@Test
public void givenTreeMultimap_whenInserting_thenReturningValuesInNaturalOrder() {
Multimap<String, String> map = TreeMultimap.create();
map.put("key1", "value3");
map.put("key1", "value1");
map.put("key1", "value2");
assertThat((Collection<String>) map.get("key1"))
.containsExactly("value1", "value2", "value3");
}
}

View File

@@ -0,0 +1,336 @@
package com.baeldung.map;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.Map.Entry;
import static org.junit.Assert.*;
public class MapUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(MapUnitTest.class);
@Test
public void givenHashMap_whenRetrievesKeyset_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put("name", "baeldung");
map.put("type", "blog");
Set<String> keys = map.keySet();
assertEquals(2, keys.size());
assertTrue(keys.contains("name"));
assertTrue(keys.contains("type"));
}
@Test
public void givenHashMap_whenRetrievesValues_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put("name", "baeldung");
map.put("type", "blog");
Collection<String> values = map.values();
assertEquals(2, values.size());
assertTrue(values.contains("baeldung"));
assertTrue(values.contains("blog"));
}
@Test
public void givenHashMap_whenRetrievesEntries_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put("name", "baeldung");
map.put("type", "blog");
Set<Entry<String, String>> entries = map.entrySet();
assertEquals(2, entries.size());
for (Entry<String, String> e : entries) {
String key = e.getKey();
String val = e.getValue();
assertTrue(key.equals("name") || key.equals("type"));
assertTrue(val.equals("baeldung") || val.equals("blog"));
}
}
@Test
public void givenKeySet_whenChangeReflectsInMap_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put("name", "baeldung");
map.put("type", "blog");
assertEquals(2, map.size());
Set<String> keys = map.keySet();
keys.remove("name");
assertEquals(1, map.size());
}
@Test(expected = ConcurrentModificationException.class)
public void givenIterator_whenFailsFastOnModification_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put("name", "baeldung");
map.put("type", "blog");
Set<String> keys = map.keySet();
Iterator<String> it = keys.iterator();
map.remove("type");
while (it.hasNext()) {
String key = it.next();
}
}
public void givenIterator_whenRemoveWorks_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put("name", "baeldung");
map.put("type", "blog");
Set<String> keys = map.keySet();
Iterator<String> it = keys.iterator();
while (it.hasNext()) {
it.next();
it.remove();
}
assertEquals(0, map.size());
}
@Test
public void whenHashCodeIsCalledOnPut_thenCorrect() {
MyKey key = new MyKey(1, "name");
Map<MyKey, String> map = new HashMap<>();
map.put(key, "val");
}
@Test
public void whenHashCodeIsCalledOnGet_thenCorrect() {
MyKey key = new MyKey(1, "name");
Map<MyKey, String> map = new HashMap<>();
map.put(key, "val");
map.get(key);
}
@Test
public void whenGetWorks_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put("key", "val");
String val = map.get("key");
assertEquals("val", val);
}
@Test
public void givenNewKey_whenPutReturnsNull_thenCorrect() {
Map<String, String> map = new HashMap<>();
String rtnVal = map.put("key1", "val1");
assertNull(rtnVal);
}
@Test
public void givenUnmappedKey_whenGetReturnsNull_thenCorrect() {
Map<String, String> map = new HashMap<>();
String rtnVal = map.get("key1");
assertNull(rtnVal);
}
@Test
public void givenNullVal_whenPutReturnsNull_thenCorrect() {
Map<String, String> map = new HashMap<>();
String rtnVal = map.put("key1", null);
assertNull(rtnVal);
}
@Test
public void givenNullKeyAndVal_whenAccepts_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put(null, null);
}
@Test
public void givenNullVal_whenRetrieves_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put("key", null);
String val = map.get("key");
assertNull(val);
}
@Test
public void whenContainsDistinguishesNullValues_thenCorrect() {
Map<String, String> map = new HashMap<>();
String val1 = map.get("key");
boolean valPresent = map.containsKey("key");
assertNull(val1);
assertFalse(valPresent);
map.put("key", null);
String val = map.get("key");
valPresent = map.containsKey("key");
assertNull(val);
assertTrue(valPresent);
}
@Test
public void whenPutReturnsPrevValue_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put("key1", "val1");
String rtnVal = map.put("key1", "val2");
assertEquals("val1", rtnVal);
}
@Test
public void whenCallsEqualsOnCollision_thenCorrect() {
HashMap<MyKey, String> map = new HashMap<>();
MyKey k1 = new MyKey(1, "firstKey");
MyKey k2 = new MyKey(2, "secondKey");
MyKey k3 = new MyKey(2, "thirdKey");
LOG.debug("storing value for k1");
map.put(k1, "firstValue");
LOG.debug("storing value for k2");
map.put(k2, "secondValue");
LOG.debug("storing value for k3");
map.put(k3, "thirdValue");
LOG.debug("retrieving value for k1");
String v1 = map.get(k1);
LOG.debug("retrieving value for k2");
String v2 = map.get(k2);
LOG.debug("retrieving value for k3");
String v3 = map.get(k3);
assertEquals("firstValue", v1);
assertEquals("secondValue", v2);
assertEquals("thirdValue", v3);
}
@Test
public void givenLinkedHashMap_whenGetsOrderedKeyset_thenCorrect() {
LinkedHashMap<Integer, String> map = new LinkedHashMap<>();
map.put(1, null);
map.put(2, null);
map.put(3, null);
map.put(4, null);
map.put(5, null);
Set<Integer> keys = map.keySet();
Integer[] arr = keys.toArray(new Integer[0]);
for (int i = 0; i < arr.length; i++) {
assertEquals(new Integer(i + 1), arr[i]);
}
}
@Test
public void givenLinkedHashMap_whenAccessOrderWorks_thenCorrect() {
LinkedHashMap<Integer, String> map = new LinkedHashMap<>(16, .75f, true);
map.put(1, null);
map.put(2, null);
map.put(3, null);
map.put(4, null);
map.put(5, null);
Set<Integer> keys = map.keySet();
assertEquals("[1, 2, 3, 4, 5]", keys.toString());
map.get(4);
assertEquals("[1, 2, 3, 5, 4]", keys.toString());
map.get(1);
assertEquals("[2, 3, 5, 4, 1]", keys.toString());
map.get(3);
assertEquals("[2, 5, 4, 1, 3]", keys.toString());
}
@Test
public void givenLinkedHashMap_whenRemovesEldestEntry_thenCorrect() {
LinkedHashMap<Integer, String> map = new MyLinkedHashMap<>(16, .75f, true);
map.put(1, null);
map.put(2, null);
map.put(3, null);
map.put(4, null);
map.put(5, null);
Set<Integer> keys = map.keySet();
assertEquals("[1, 2, 3, 4, 5]", keys.toString());
map.put(6, null);
assertEquals("[2, 3, 4, 5, 6]", keys.toString());
map.put(7, null);
assertEquals("[3, 4, 5, 6, 7]", keys.toString());
map.put(8, null);
assertEquals("[4, 5, 6, 7, 8]", keys.toString());
}
@Test
public void givenTreeMap_whenOrdersEntriesNaturally_thenCorrect() {
TreeMap<Integer, String> map = new TreeMap<>();
map.put(3, "val");
map.put(2, "val");
map.put(1, "val");
map.put(5, "val");
map.put(4, "val");
assertEquals("[1, 2, 3, 4, 5]", map.keySet().toString());
}
@Test
public void givenTreeMap_whenOrdersEntriesNaturally_thenCorrect2() {
TreeMap<String, String> map = new TreeMap<>();
map.put("c", "val");
map.put("b", "val");
map.put("a", "val");
map.put("e", "val");
map.put("d", "val");
assertEquals("[a, b, c, d, e]", map.keySet().toString());
}
@Test
public void givenTreeMap_whenOrdersEntriesByComparator_thenCorrect() {
TreeMap<Integer, String> map = new TreeMap<>(Comparator.reverseOrder());
map.put(3, "val");
map.put(2, "val");
map.put(1, "val");
map.put(5, "val");
map.put(4, "val");
assertEquals("[5, 4, 3, 2, 1]", map.keySet().toString());
}
@Test
public void givenTreeMap_whenPerformsQueries_thenCorrect() {
TreeMap<Integer, String> map = new TreeMap<>();
map.put(3, "val");
map.put(2, "val");
map.put(1, "val");
map.put(5, "val");
map.put(4, "val");
Integer highestKey = map.lastKey();
Integer lowestKey = map.firstKey();
Set<Integer> keysLessThan3 = map.headMap(3).keySet();
Set<Integer> keysGreaterThanEqTo3 = map.tailMap(3).keySet();
assertEquals(new Integer(5), highestKey);
assertEquals(new Integer(1), lowestKey);
assertEquals("[1, 2]", keysLessThan3.toString());
assertEquals("[3, 4, 5]", keysGreaterThanEqTo3.toString());
}
}

View File

@@ -0,0 +1,103 @@
/**
*
*/
package com.baeldung.map;
import com.google.common.collect.HashBiMap;
import org.apache.commons.collections4.BidiMap;
import org.apache.commons.collections4.bidimap.DualHashBidiMap;
import org.junit.Test;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.stream.Collectors;
import static org.junit.Assert.assertEquals;
/**
* @author swpraman
*
*/
public class MapUtilUnitTest {
@Test
public void whenUsingImperativeWayForSingleKey_shouldReturnSingleKey() {
Map<String, String> capitalCountryMap = new HashMap<>();
capitalCountryMap.put("Tokyo", "Japan");
capitalCountryMap.put("New Delhi", "India");
assertEquals("New Delhi", MapUtil.getKey(capitalCountryMap, "India"));
}
@Test
public void whenUsingImperativeWayForAllKeys_shouldReturnAllKeys() {
Map<String, String> capitalCountryMap = new HashMap<>();
capitalCountryMap.put("Tokyo", "Japan");
capitalCountryMap.put("Berlin", "Germany");
capitalCountryMap.put("Cape Town", "South Africa");
capitalCountryMap.put("Pretoria", "South Africa");
capitalCountryMap.put("Bloemfontein", "South Africa");
assertEquals(new HashSet<String>(Arrays.asList(
new String[] {"Cape Town", "Pretoria", "Bloemfontein"})),
MapUtil.getKeys(capitalCountryMap, "South Africa"));
}
@Test
public void whenUsingFunctionalWayForSingleKey_shouldReturnSingleKey() {
Map<String, String> capitalCountryMap = new HashMap<>();
capitalCountryMap.put("Tokyo", "Japan");
capitalCountryMap.put("Berlin", "Germany");
assertEquals("Berlin", MapUtil.keys(capitalCountryMap, "Germany").findFirst().get());
}
@Test
public void whenUsingFunctionalWayForAllKeys_shouldReturnAllKeys() {
Map<String, String> capitalCountryMap = new HashMap<>();
capitalCountryMap.put("Tokyo", "Japan");
capitalCountryMap.put("Berlin", "Germany");
capitalCountryMap.put("Cape Town", "South Africa");
capitalCountryMap.put("Pretoria", "South Africa");
capitalCountryMap.put("Bloemfontein", "South Africa");
assertEquals(new HashSet<String>(Arrays.asList(
new String[] {"Cape Town", "Pretoria", "Bloemfontein"})),
MapUtil.keys(capitalCountryMap, "South Africa").collect(Collectors.toSet()));
}
@Test
public void whenUsingBidiMap_shouldReturnKey() {
BidiMap<String, String> capitalCountryMap = new DualHashBidiMap<String, String>();
capitalCountryMap.put("Berlin", "Germany");
capitalCountryMap.put("Cape Town", "South Africa");
assertEquals("Berlin", capitalCountryMap.getKey("Germany"));
}
@Test
public void whenUsingBidiMapAddDuplicateValue_shouldRemoveOldEntry() {
BidiMap<String, String> capitalCountryMap = new DualHashBidiMap<String, String>();
capitalCountryMap.put("Berlin", "Germany");
capitalCountryMap.put("Cape Town", "South Africa");
capitalCountryMap.put("Pretoria", "South Africa");
assertEquals("Pretoria", capitalCountryMap.getKey("South Africa"));
}
@Test
public void whenUsingBiMap_shouldReturnKey() {
HashBiMap<String, String> capitalCountryMap = HashBiMap.create();
capitalCountryMap.put("Berlin", "Germany");
capitalCountryMap.put("Cape Town", "South Africa");
assertEquals("Berlin", capitalCountryMap.inverse().get("Germany"));
}
@Test(expected=IllegalArgumentException.class)
public void whenUsingBiMapAddDuplicateValue_shouldThrowException() {
HashBiMap<String, String> capitalCountryMap = HashBiMap.create();
capitalCountryMap.put("Berlin", "Germany");
capitalCountryMap.put("Cape Town", "South Africa");
capitalCountryMap.put("Pretoria", "South Africa");
assertEquals("Berlin", capitalCountryMap.inverse().get("Germany"));
}
}

View File

@@ -0,0 +1,227 @@
package com.baeldung.map;
import org.apache.commons.collections4.MultiMapUtils;
import org.apache.commons.collections4.MultiSet;
import org.apache.commons.collections4.MultiValuedMap;
import org.apache.commons.collections4.multimap.ArrayListValuedHashMap;
import org.apache.commons.collections4.multimap.HashSetValuedHashMap;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
public class MultiValuedMapUnitTest {
@Test
public void givenMultiValuesMap_whenPuttingMultipleValuesUsingPutMethod_thenReturningAllValues() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("fruits", "apple");
map.put("fruits", "orange");
assertThat((Collection<String>) map.get("fruits")).containsExactly("apple", "orange");
}
@Test
public void givenMultiValuesMap_whenPuttingMultipleValuesUsingPutAllMethod_thenReturningAllValues() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.putAll("vehicles", Arrays.asList("car", "bike"));
assertThat((Collection<String>) map.get("vehicles")).containsExactly("car", "bike");
}
@Test
public void givenMultiValuesMap_whenGettingValueUsingGetMethod_thenReturningValue() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("fruits", "apple");
assertThat((Collection<String>) map.get("fruits")).containsExactly("apple");
}
@Test
public void givenMultiValuesMap_whenUsingEntriesMethod_thenReturningMappings() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("fruits", "apple");
map.put("fruits", "orange");
Collection<Entry<String, String>> entries = (Collection<Entry<String, String>>) map.entries();
for(Map.Entry<String,String> entry : entries) {
assertThat(entry.getKey()).contains("fruits");
assertTrue(entry.getValue().equals("apple") || entry.getValue().equals("orange") );
}
}
@Test
public void givenMultiValuesMap_whenUsingKeysMethod_thenReturningAllKeys() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("fruits", "apple");
map.put("fruits", "orange");
map.put("vehicles", "car");
map.put("vehicles", "bike");
MultiSet<String> keys = map.keys();
assertThat((keys)).contains("fruits", "vehicles");
}
@Test
public void givenMultiValuesMap_whenUsingKeySetMethod_thenReturningAllKeys() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("fruits", "apple");
map.put("fruits", "orange");
map.put("vehicles", "car");
map.put("vehicles", "bike");
Set<String> keys = map.keySet();
assertThat(keys).contains("fruits", "vehicles");
}
@Test
public void givenMultiValuesMap_whenUsingValuesMethod_thenReturningAllValues() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("fruits", "apple");
map.put("fruits", "orange");
map.put("vehicles", "car");
map.put("vehicles", "bike");
assertThat(((Collection<String>) map.values())).contains("apple", "orange", "car", "bike");
}
@Test
public void givenMultiValuesMap_whenUsingRemoveMethod_thenReturningUpdatedMap() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("fruits", "apple");
map.put("fruits", "orange");
map.put("vehicles", "car");
map.put("vehicles", "bike");
assertThat(((Collection<String>) map.values())).contains("apple", "orange", "car", "bike");
map.remove("fruits");
assertThat(((Collection<String>) map.values())).contains("car", "bike");
}
@Test
public void givenMultiValuesMap_whenUsingRemoveMappingMethod_thenReturningUpdatedMapAfterMappingRemoved() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("fruits", "apple");
map.put("fruits", "orange");
map.put("vehicles", "car");
map.put("vehicles", "bike");
assertThat(((Collection<String>) map.values())).contains("apple", "orange", "car", "bike");
map.removeMapping("fruits", "apple");
assertThat(((Collection<String>) map.values())).contains("orange", "car", "bike");
}
@Test
public void givenMultiValuesMap_whenUsingClearMethod_thenReturningEmptyMap() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("fruits", "apple");
map.put("fruits", "orange");
map.put("vehicles", "car");
map.put("vehicles", "bike");
assertThat(((Collection<String>) map.values())).contains("apple", "orange", "car", "bike");
map.clear();
assertTrue(map.isEmpty());
}
@Test
public void givenMultiValuesMap_whenUsingContainsKeyMethod_thenReturningTrue() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("fruits", "apple");
map.put("fruits", "orange");
map.put("vehicles", "car");
map.put("vehicles", "bike");
assertTrue(map.containsKey("fruits"));
}
@Test
public void givenMultiValuesMap_whenUsingContainsValueMethod_thenReturningTrue() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("fruits", "apple");
map.put("fruits", "orange");
map.put("vehicles", "car");
map.put("vehicles", "bike");
assertTrue(map.containsValue("orange"));
}
@Test
public void givenMultiValuesMap_whenUsingIsEmptyMethod_thenReturningFalse() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("fruits", "apple");
map.put("fruits", "orange");
map.put("vehicles", "car");
map.put("vehicles", "bike");
assertFalse(map.isEmpty());
}
@Test
public void givenMultiValuesMap_whenUsingSizeMethod_thenReturningElementCount() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("fruits", "apple");
map.put("fruits", "orange");
map.put("vehicles", "car");
map.put("vehicles", "bike");
assertEquals(4, map.size());
}
@Test
public void givenArrayListValuedHashMap_whenPuttingDoubleValues_thenReturningAllValues() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("fruits", "apple");
map.put("fruits", "orange");
map.put("fruits", "orange");
assertThat((Collection<String>) map.get("fruits")).containsExactly("apple", "orange", "orange");
}
@Test
public void givenHashSetValuedHashMap_whenPuttingTwiceTheSame_thenReturningOneValue() {
MultiValuedMap<String, String> map = new HashSetValuedHashMap<>();
map.put("fruits", "apple");
map.put("fruits", "apple");
assertThat((Collection<String>) map.get("fruits")).containsExactly("apple");
}
@Test(expected = UnsupportedOperationException.class)
public void givenUnmodifiableMultiValuedMap_whenInserting_thenThrowingException() {
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("fruits", "apple");
map.put("fruits", "orange");
MultiValuedMap<String, String> immutableMap = MultiMapUtils.unmodifiableMultiValuedMap(map);
immutableMap.put("fruits", "banana");
}
}