JAVA-12730: Rename java-collections-maps-3 to

core-java-collections-maps-5
This commit is contained in:
sampadawagde
2022-06-26 16:25:51 +05:30
parent 0f2bfac43f
commit 2a329a09d1
24 changed files with 2 additions and 2 deletions

View File

@@ -0,0 +1,10 @@
### Relevant Articles:
- [Java Map With Case-Insensitive Keys](https://www.baeldung.com/java-map-with-case-insensitive-keys)
- [Using a Byte Array as Map Key in Java](https://www.baeldung.com/java-map-key-byte-array)
- [Using the Map.Entry Java Class](https://www.baeldung.com/java-map-entry)
- [Optimizing HashMaps Performance](https://www.baeldung.com/java-hashmap-optimize-performance)
- [Update the Value Associated With a Key in a HashMap](https://www.baeldung.com/java-hashmap-update-value-by-key)
- [Java Map keySet() vs. entrySet() vs. values() Methods](https://www.baeldung.com/java-map-entries-methods)
- [Java IdentityHashMap Class and Its Use Cases](https://www.baeldung.com/java-identityhashmap)
- [How to Invert a Map in Java](https://www.baeldung.com/java-invert-map)

View File

@@ -0,0 +1,41 @@
<?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-5</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-collections-maps-5</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit-jupiter.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
</dependencies>
<properties>
<spring.version>5.2.5.RELEASE</spring.version>
</properties>
</project>

View File

@@ -0,0 +1,28 @@
package com.baeldung.map.bytearrays;
import java.util.Arrays;
public final class BytesKey {
private final byte[] array;
public BytesKey(byte[] array) {
this.array = array;
}
public byte[] getArray() {
return array.clone();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BytesKey bytesKey = (BytesKey) o;
return Arrays.equals(array, bytesKey.array);
}
@Override
public int hashCode() {
return Arrays.hashCode(array);
}
}

View File

@@ -0,0 +1,35 @@
package com.baeldung.map.entry;
public class Book {
private String title;
private String author;
public Book(String title, String author) {
this.title = title;
this.author = author;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
@Override
public String toString() {
return "Book{" +
"title='" + title + '\'' +
", author='" + author + '\'' +
'}';
}
}

View File

@@ -0,0 +1,34 @@
package com.baeldung.map.entry;
import java.util.HashMap;
import java.util.Map;
public class MapEntryEfficiencyExample {
public static void main(String[] args) {
MapEntryEfficiencyExample mapEntryEfficiencyExample = new MapEntryEfficiencyExample();
Map<String, String> map = new HashMap<>();
map.put("Robert C. Martin", "Clean Code");
map.put("Joshua Bloch", "Effective Java");
System.out.println("Iterating Using Map.KeySet - 2 operations");
mapEntryEfficiencyExample.usingKeySet(map);
System.out.println("Iterating Using Map.Entry - 1 operation");
mapEntryEfficiencyExample.usingEntrySet(map);
}
public void usingKeySet(Map<String, String> bookMap) {
for (String key : bookMap.keySet()) {
System.out.println("key: " + key + " value: " + bookMap.get(key));
}
}
public void usingEntrySet(Map<String, String> bookMap) {
for (Map.Entry<String, String> book: bookMap.entrySet()) {
System.out.println("key: " + book.getKey() + " value: " + book.getValue());
}
}
}

View File

@@ -0,0 +1,25 @@
package com.baeldung.map.entry;
import java.util.*;
public class MapEntryTupleExample {
public static void main(String[] args) {
Map.Entry<String, Book> tuple1;
Map.Entry<String, Book> tuple2;
Map.Entry<String, Book> tuple3;
tuple1 = new AbstractMap.SimpleEntry<>("9780134685991", new Book("Effective Java 3d Edition", "Joshua Bloch"));
tuple2 = new AbstractMap.SimpleEntry<>("9780132350884", new Book("Clean Code", "Robert C Martin"));
tuple3 = new AbstractMap.SimpleEntry<>("9780132350884", new Book("Clean Code", "Robert C Martin"));
List<Map.Entry<String, Book>> orderedTuples = new ArrayList<>();
orderedTuples.add(tuple1);
orderedTuples.add(tuple2);
orderedTuples.add(tuple3);
for (Map.Entry<String, Book> tuple : orderedTuples) {
System.out.println("key: " + tuple.getKey() + " value: " + tuple.getValue());
}
}
}

View File

@@ -0,0 +1,6 @@
package com.baeldung.map.hashing;
class Member {
Integer id;
String name;
}

View File

@@ -0,0 +1,8 @@
package com.baeldung.map.hashing;
public class MemberWithBadHashing extends Member {
@Override
public int hashCode() {
return name.hashCode();
}
}

View File

@@ -0,0 +1,18 @@
package com.baeldung.map.hashing;
import com.google.common.base.Charsets;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
public class MemberWithGuavaHashing extends Member {
@Override
public int hashCode() {
HashFunction hashFunction = Hashing.murmur3_32();
return hashFunction.newHasher()
.putInt(id)
.putString(name, Charsets.UTF_8)
.hash().hashCode();
}
}

View File

@@ -0,0 +1,18 @@
package com.baeldung.map.hashing;
public class MemberWithId extends Member {
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MemberWithId that = (MemberWithId) o;
return id.equals(that.id);
}
@Override
public int hashCode() {
return id;
}
}

View File

@@ -0,0 +1,23 @@
package com.baeldung.map.hashing;
import java.util.Objects;
public class MemberWithIdAndName extends Member {
public static final int PRIME = 31;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MemberWithObjects that = (MemberWithObjects) o;
return Objects.equals(id, that.id) &&
Objects.equals(name, that.name);
}
@Override
public int hashCode() {
int result = id.hashCode();
result = PRIME * result + (name == null ? 0 : name.hashCode());
return result;
}
}

View File

@@ -0,0 +1,19 @@
package com.baeldung.map.hashing;
import java.util.Objects;
public class MemberWithObjects extends Member {
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MemberWithObjects that = (MemberWithObjects) o;
return Objects.equals(id, that.id) &&
Objects.equals(name, that.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
}

View File

@@ -0,0 +1,156 @@
package com.baeldung.map.identity;
import java.util.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class IdentityHashMapDemonstrator {
public static void main(String[] args) {
IdentityHashMap<String, String> identityHashMap = createWithSimpleData();
System.out.println("Map details: " + identityHashMap);
IdentityHashMap<String, String> copiedMap = createFromAnotherMap(identityHashMap);
updateWithNewValue(copiedMap);
iterateIdentityHashMap(copiedMap);
addNullKeyValue();
demoHashMapVsIdentityMap();
demoMutableKeys();
Map<String, String> synchronizedMap = getSynchronizedMap();
//Do multithreaded operations on synchronizedMap
}
private static void addNullKeyValue() {
IdentityHashMap<String, String> identityHashMap = new IdentityHashMap<>();
identityHashMap.put(null, "Null Key Accepted");
identityHashMap.put("Null Value Accepted", null);
assertEquals("Null Key Accepted", identityHashMap.get(null));
assertEquals(null, identityHashMap.get("Null Value Accepted"));
}
private static void iterateIdentityHashMap(IdentityHashMap<String, String> identityHashMap) {
// Iterating using entrySet
System.out.println("Iterating values: ");
Set<Map.Entry<String, String>> entries = identityHashMap.entrySet();
for (Map.Entry<String, String> entry: entries) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
// Iterating using keySet
System.out.println("Iterating values using keySet: ");
for (String key: identityHashMap.keySet()) {
System.out.println(key + ": " + identityHashMap.get(key));
}
// Throws error if we modify while iterating
System.out.println("This iteration throws error: ");
try {
for (Map.Entry<String, String> entry: entries) {
System.out.println(entry.getKey() + ": " + entry.getValue());
identityHashMap.remove("title");
}
} catch (ConcurrentModificationException ex) {
System.out.println("This exception will raise for sure, if we modify while iterating");
}
}
private static class Book {
String title;
int year;
Book() {
// nothing to do
}
Book(String title, int year) {
this.title = title;
this.year = year;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Book book = (Book) o;
return year == book.year && title.equals(book.title);
}
@Override
public int hashCode() {
return Objects.hash(title, year);
}
@Override
public String toString() {
return "Book{title='" + title + "', year=" + year + "}";
}
}
private static void demoMutableKeys() {
Book book1 = new Book("A Passage to India", 1924);
Book book2 = new Book("Invisible Man", 1953);
HashMap<Book, String> hashMap = new HashMap<>(10);
hashMap.put(book1, "A great work of fiction");
hashMap.put(book2, "won the US National Book Award");
book2.year = 1952;
assertEquals(null, hashMap.get(book2));
System.out.println("HashMap: " + hashMap);
IdentityHashMap<Book, String> identityHashMap = new IdentityHashMap<>(10);
identityHashMap.put(book1, "A great work of fiction");
identityHashMap.put(book2, "won the US National Book Award");
book2.year = 1951;
assertEquals("won the US National Book Award", identityHashMap.get(book2));
System.out.println("IdentityHashMap: " + identityHashMap);
}
private static void demoHashMapVsIdentityMap() {
IdentityHashMap<String, String> identityHashMap = new IdentityHashMap<>();
identityHashMap.put("title", "Harry Potter and the Goblet of Fire");
identityHashMap.put("author", "J. K. Rowling");
identityHashMap.put("language", "English");
identityHashMap.put("genre", "Fantasy");
HashMap<String, String> hashMap = new HashMap<>(identityHashMap);
hashMap.put(new String("genre"), "Drama");
assertEquals(4, hashMap.size());
System.out.println("HashMap content: " + hashMap);
identityHashMap.put(new String("genre"), "Drama");
assertEquals(5, identityHashMap.size());
System.out.println("IdentityHashMap content: " + identityHashMap);
}
private static Map<String, String> getSynchronizedMap() {
Map<String, String> synchronizedMap = Collections.synchronizedMap(new IdentityHashMap<String, String>());
return synchronizedMap;
}
private static IdentityHashMap<String, String> createFromAnotherMap(Map<String, String> otherMap) {
IdentityHashMap<String, String> identityHashMap = new IdentityHashMap<>(otherMap);
return identityHashMap;
}
private static void updateWithNewValue(IdentityHashMap<String, String> identityHashMap) {
String oldTitle = identityHashMap.put("title", "Harry Potter and the Deathly Hallows");
assertEquals("Harry Potter and the Goblet of Fire", oldTitle);
assertEquals("Harry Potter and the Deathly Hallows", identityHashMap.get("title"));
}
public static void addValue(IdentityHashMap<String, String> identityHashMap, String key, String value) {
identityHashMap.put(key, value);
}
public static void addAllValues(IdentityHashMap<String, String> identityHashMap, Map<String, String> otherMap) {
identityHashMap.putAll(otherMap);
}
public static IdentityHashMap<String, String> createWithSimpleData() {
IdentityHashMap<String, String> identityHashMap = new IdentityHashMap<>();
identityHashMap.put("title", "Harry Potter and the Goblet of Fire");
identityHashMap.put("author", "J. K. Rowling");
identityHashMap.put("language", "English");
identityHashMap.put("genre", "Fantasy");
return identityHashMap;
}
}

View File

@@ -0,0 +1,59 @@
package com.baeldung.map.invert;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
public class InvertHashMapExample {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("first", 1);
map.put("second", 2);
System.out.println(map);
invertMapUsingForLoop(map);
invertMapUsingStreams(map);
invertMapUsingMapper(map);
map.put("two", 2);
invertMapUsingGroupingBy(map);
}
public static <V, K> Map<V, K> invertMapUsingForLoop(Map<K, V> map) {
Map<V, K> inversedMap = new HashMap<V, K>();
for (Entry<K, V> entry : map.entrySet()) {
inversedMap.put(entry.getValue(), entry.getKey());
}
System.out.println(inversedMap);
return inversedMap;
}
public static <V, K> Map<V, K> invertMapUsingStreams(Map<K, V> map) {
Map<V, K> inversedMap = map.entrySet()
.stream()
.collect(Collectors.toMap(Entry::getValue, Entry::getKey));
System.out.println(inversedMap);
return inversedMap;
}
public static <K, V> Map<V, K> invertMapUsingMapper(Map<K, V> sourceMap) {
Map<V, K> inversedMap = sourceMap.entrySet()
.stream()
.collect(Collectors.toMap(Entry::getValue, Entry::getKey, (oldValue, newValue) -> oldValue));
System.out.println(inversedMap);
return inversedMap;
}
public static <V, K> Map<V, List<K>> invertMapUsingGroupingBy(Map<K, V> map) {
Map<V, List<K>> inversedMap = map.entrySet()
.stream()
.collect(Collectors.groupingBy(Map.Entry::getValue, Collectors.mapping(Map.Entry::getKey, Collectors.toList())));
System.out.println(inversedMap);
return inversedMap;
}
}

View File

@@ -0,0 +1,104 @@
package com.baeldung.map.bytearrays;
import com.google.common.collect.ImmutableList;
import org.junit.jupiter.api.Test;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
class ByteArrayKeyUnitTest {
@Test
void givenPrimitiveByteArrayKey_whenRetrievingFromMap_shouldRetrieveDifferentObjects() {
// given
byte[] key1 = {1, 2, 3};
byte[] key2 = {1, 2, 3};
String value1 = "value1";
String value2 = "value2";
Map<byte[], String> map = new HashMap<>();
map.put(key1, value1);
map.put(key2, value2);
// when
String retrievedValue1 = map.get(key1);
String retrievedValue2 = map.get(key2);
String retrievedValue3 = map.get(new byte[]{1, 2, 3});
// then
assertThat(retrievedValue1).isEqualTo(value1);
assertThat(retrievedValue2).isEqualTo(value2);
assertThat(retrievedValue3).isNull();
}
@Test
void givenEncodedStringKey_whenRetrievingFromMap_shouldRetrieveLastPutObject() {
// given
String key1 = Base64.getEncoder().encodeToString(new byte[]{1, 2, 3});
String key2 = Base64.getEncoder().encodeToString(new byte[]{1, 2, 3});
String value1 = "value1";
String value2 = "value2";
Map<String, String> map = new HashMap<>();
map.put(key1, value1);
map.put(key2, value2);
// when
String retrievedValue1 = map.get(key1);
String retrievedValue2 = map.get(key2);
// then
assertThat(key1).isEqualTo(key2);
assertThat(retrievedValue1).isEqualTo(value2);
assertThat(retrievedValue2).isEqualTo(value2);
assertThat(retrievedValue1).isEqualTo(retrievedValue2);
}
@Test
void givenByteListKey_whenRetrievingFromMap_shouldRetrieveLastPutObject() {
// given
List<Byte> key1 = ImmutableList.of((byte)1, (byte)2, (byte)3);
List<Byte> key2 = ImmutableList.of((byte)1, (byte)2, (byte)3);
String value1 = "value1";
String value2 = "value2";
Map<List<Byte>, String> map = new HashMap<>();
map.put(key1, value1);
map.put(key2, value2);
// when
String retrievedValue1 = map.get(key1);
String retrievedValue2 = map.get(key2);
// then
assertThat(key1).isEqualTo(key2);
assertThat(retrievedValue1).isEqualTo(value2);
assertThat(retrievedValue2).isEqualTo(value2);
assertThat(retrievedValue1).isEqualTo(retrievedValue2);
}
@Test
void givenCustomWrapperKey_whenRetrievingFromMap_shouldRetrieveLastPutObject() {
// given
BytesKey key1 = new BytesKey(new byte[]{1, 2, 3});
BytesKey key2 = new BytesKey(new byte[]{1, 2, 3});
String value1 = "value1";
String value2 = "value2";
Map<BytesKey, String> map = new HashMap<>();
map.put(key1, value1);
map.put(key2, value2);
// when
String retrievedValue1 = map.get(key1);
String retrievedValue2 = map.get(key2);
String retrievedValue3 = map.get(new BytesKey(new byte[]{1, 2, 3}));
// then
assertThat(key1).isEqualTo(key2);
assertThat(retrievedValue1).isEqualTo(value2);
assertThat(retrievedValue2).isEqualTo(value2);
assertThat(retrievedValue1).isEqualTo(retrievedValue2);
assertThat(retrievedValue3).isEqualTo(value2);
}
}

View File

@@ -0,0 +1,94 @@
package com.baeldung.map.caseinsensitivekeys;
import org.apache.commons.collections4.map.CaseInsensitiveMap;
import org.junit.Test;
import org.springframework.util.LinkedCaseInsensitiveMap;
import java.util.Map;
import java.util.TreeMap;
import static org.junit.Assert.*;
public class CaseInsensitiveMapUnitTest {
@Test
public void givenCaseInsensitiveTreeMap_whenTwoEntriesAdded_thenSizeIsOne(){
Map<String, Integer> treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
treeMap.put("abc", 1);
treeMap.put("ABC", 2);
assertEquals(1, treeMap.size());
}
@Test
public void givenCommonsCaseInsensitiveMap_whenTwoEntriesAdded_thenSizeIsOne(){
Map<String, Integer> commonsHashMap = new CaseInsensitiveMap<>();
commonsHashMap.put("abc", 1);
commonsHashMap.put("ABC", 2);
assertEquals(1, commonsHashMap.size());
}
@Test
public void givenLinkedCaseInsensitiveMap_whenTwoEntriesAdded_thenSizeIsOne(){
Map<String, Integer> linkedHashMap = new LinkedCaseInsensitiveMap<>();
linkedHashMap.put("abc", 1);
linkedHashMap.put("ABC", 2);
assertEquals(1, linkedHashMap.size());
}
@Test
public void givenCaseInsensitiveTreeMap_whenSameEntryAdded_thenValueUpdated(){
Map<String, Integer> treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
treeMap.put("abc", 1);
treeMap.put("ABC", 2);
assertEquals(2, treeMap.get("aBc").intValue());
assertEquals(2, treeMap.get("ABc").intValue());
}
@Test
public void givenCommonsCaseInsensitiveMap_whenSameEntryAdded_thenValueUpdated(){
Map<String, Integer> commonsHashMap = new CaseInsensitiveMap<>();
commonsHashMap.put("abc", 1);
commonsHashMap.put("ABC", 2);
assertEquals(2, commonsHashMap.get("aBc").intValue());
assertEquals(2, commonsHashMap.get("ABc").intValue());
}
@Test
public void givenLinkedCaseInsensitiveMap_whenSameEntryAdded_thenValueUpdated(){
Map<String, Integer> linkedHashMap = new LinkedCaseInsensitiveMap<>();
linkedHashMap.put("abc", 1);
linkedHashMap.put("ABC", 2);
assertEquals(2, linkedHashMap.get("aBc").intValue());
assertEquals(2, linkedHashMap.get("ABc").intValue());
}
@Test
public void givenCaseInsensitiveTreeMap_whenEntryRemoved_thenSizeIsZero(){
Map<String, Integer> treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
treeMap.put("abc", 3);
treeMap.remove("aBC");
assertEquals(0, treeMap.size());
}
@Test
public void givenCommonsCaseInsensitiveMap_whenEntryRemoved_thenSizeIsZero(){
Map<String, Integer> commonsHashMap = new CaseInsensitiveMap<>();
commonsHashMap.put("abc", 3);
commonsHashMap.remove("aBC");
assertEquals(0, commonsHashMap.size());
}
@Test
public void givenLinkedCaseInsensitiveMap_whenEntryRemoved_thenSizeIsZero(){
Map<String, Integer> linkedHashMap = new LinkedCaseInsensitiveMap<>();
linkedHashMap.put("abc", 3);
linkedHashMap.remove("aBC");
assertEquals(0, linkedHashMap.size());
}
}

View File

@@ -0,0 +1,33 @@
package com.baeldung.map.entry;
import org.junit.Test;
import java.util.*;
import static org.junit.Assert.assertEquals;
public class MapEntryUnitTest {
@Test
public void givenSimpleEntryList_whenAddDuplicateKey_thenDoesNotOverwriteExistingKey() {
List<Map.Entry<String, Book>> orderedTuples = new ArrayList<>();
orderedTuples.add(new AbstractMap.SimpleEntry<>("9780134685991", new Book("Effective Java 3d Edition", "Joshua Bloch")));
orderedTuples.add(new AbstractMap.SimpleEntry<>("9780132350884", new Book("Clean Code", "Robert C Martin")));
orderedTuples.add(new AbstractMap.SimpleEntry<>("9780132350884", new Book("Clean Code", "Robert C Martin")));
assertEquals(3, orderedTuples.size());
assertEquals("9780134685991", orderedTuples.get(0).getKey());
assertEquals("9780132350884", orderedTuples.get(1).getKey());
assertEquals("9780132350884", orderedTuples.get(2).getKey());
}
@Test
public void givenRegularMap_whenAddDuplicateKey_thenOverwritesExistingKey() {
Map<String, Book> entries = new HashMap<>();
entries.put("9780134685991", new Book("Effective Java 3d Edition", "Joshua Bloch"));
entries.put("9780132350884", new Book("Clean Code", "Robert C Martin"));
entries.put("9780132350884", new Book("Clean Code", "Robert C Martin"));
assertEquals(2, entries.size());
}
}

View File

@@ -0,0 +1,126 @@
package com.baeldung.map.hashing;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiFunction;
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class HashMapUpdateUnitTest {
Map<String, Double> fruitMap = new HashMap<>();
@BeforeAll
void setup() {
fruitMap.put("apple", 2.45);
fruitMap.put("grapes", 1.22);
}
@Test
public void givenFruitMap_whenPuttingAList_thenHashMapUpdatesAndInsertsValues() {
Double newValue = 2.11;
fruitMap.put("apple", newValue);
fruitMap.put("orange", newValue);
Assertions.assertEquals(newValue, fruitMap.get("apple"));
Assertions.assertTrue(fruitMap.containsKey("orange"));
Assertions.assertEquals(newValue, fruitMap.get("orange"));
}
@Test
public void givenFruitMap_whenKeyExists_thenValuesUpdated() {
double newValue = 2.31;
if (fruitMap.containsKey("apple")) {
fruitMap.put("apple", newValue);
}
Assertions.assertEquals(Double.valueOf(newValue), fruitMap.get("apple"));
}
@Test
public void givenFruitMap_whenReplacingOldValue_thenNewValueSet() {
double newPrice = 3.22;
Double applePrice = fruitMap.get("apple");
Double oldValue = fruitMap.replace("apple", newPrice);
Assertions.assertNotNull(oldValue);
Assertions.assertEquals(oldValue, applePrice);
Assertions.assertEquals(Double.valueOf(newPrice), fruitMap.get("apple"));
}
@Test
public void givenFruitMap_whenReplacingWithRealOldValue_thenNewValueSet() {
double newPrice = 3.22;
Double applePrice = fruitMap.get("apple");
boolean isUpdated = fruitMap.replace("apple", applePrice, newPrice);
Assertions.assertTrue(isUpdated);
}
@Test
public void givenFruitMap_whenReplacingWithWrongOldValue_thenNewValueNotSet() {
double newPrice = 3.22;
boolean isUpdated = fruitMap.replace("apple", Double.valueOf(0), newPrice);
Assertions.assertFalse(isUpdated);
}
@Test
public void givenFruitMap_whenGetOrDefaultUsedWithPut_thenNewEntriesAdded() {
fruitMap.put("plum", fruitMap.getOrDefault("plum", 2.41));
Assertions.assertTrue(fruitMap.containsKey("plum"));
Assertions.assertEquals(Double.valueOf(2.41), fruitMap.get("plum"));
}
@Test
public void givenFruitMap_whenPutIfAbsentUsed_thenNewEntriesAdded() {
double newValue = 1.78;
fruitMap.putIfAbsent("apple", newValue);
fruitMap.putIfAbsent("pear", newValue);
Assertions.assertTrue(fruitMap.containsKey("pear"));
Assertions.assertNotEquals(Double.valueOf(newValue), fruitMap.get("apple"));
Assertions.assertEquals(Double.valueOf(newValue), fruitMap.get("pear"));
}
@Test
public void givenFruitMap_whenComputeUsed_thenValueUpdated() {
double oldPrice = fruitMap.get("apple");
BiFunction<Double, Integer, Double> powFunction = (x1, x2) -> Math.pow(x1, x2);
fruitMap.compute(
"apple", (k, v) -> powFunction.apply(v, 2));
Assertions.assertEquals(
Double.valueOf(Math.pow(oldPrice, 2)), fruitMap.get("apple"));
Assertions.assertThrows(
NullPointerException.class, () -> fruitMap.compute("blueberry", (k, v) -> powFunction.apply(v, 2)));
}
@Test
public void givenFruitMap_whenComputeIfAbsentUsed_thenNewEntriesAdded() {
fruitMap.computeIfAbsent(
"lemon", k -> Double.valueOf(k.length()));
Assertions.assertTrue(fruitMap.containsKey("lemon"));
Assertions.assertEquals(Double.valueOf("lemon".length()), fruitMap.get("lemon"));
}
@Test
public void givenFruitMap_whenComputeIfPresentUsed_thenValuesUpdated() {
Double oldAppleValue = fruitMap.get("apple");
BiFunction<Double, Integer, Double> powFunction = (x1, x2) -> Math.pow(x1, x2);
fruitMap.computeIfPresent(
"apple", (k, v) -> powFunction.apply(v, 2));
Assertions.assertEquals(Double.valueOf(Math.pow(oldAppleValue, 2)), fruitMap.get("apple"));
}
@Test
public void givenFruitMap_whenMergeUsed_thenNewEntriesAdded() {
double defaultValue = 1.25;
BiFunction<Double, Integer, Double> powFunction = (x1, x2) -> Math.pow(x1, x2);
fruitMap.merge(
"apple", defaultValue, (k, v) -> powFunction.apply(v, 2));
fruitMap.merge(
"strawberry", defaultValue, (k, v) -> powFunction.apply(v, 2));
Assertions.assertTrue(fruitMap.containsKey("strawberry"));
Assertions.assertEquals(Double.valueOf(defaultValue), fruitMap.get("strawberry"));
Assertions.assertEquals(Double.valueOf(Math.pow(defaultValue, 2)), fruitMap.get("apple"));
}
}

View File

@@ -0,0 +1,76 @@
package com.baeldung.map.hashing;
import com.google.common.base.Stopwatch;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.HashMap;
import java.util.SplittableRandom;
import java.util.function.Supplier;
public class HashingUnitTest {
public static final int SAMPLES = 1000000;
private SplittableRandom random = new SplittableRandom();
private String[] names = {"John", "Adam", "Suzie"};
@Test
void givenPrimitiveByteArrayKey_whenRetrievingFromMap_shouldRetrieveDifferentObjects() {
// bad hashing example is prohibitively slow for bigger samples
// Duration[] badHashing = testDuration(MemberWithBadHashing::new);
Duration[] withId = testDuration(MemberWithId::new);
Duration[] withObjects = testDuration(MemberWithObjects::new);
Duration[] withIdAndName = testDuration(MemberWithIdAndName::new);
// System.out.println("Inserting with bad hashing:");
// System.out.println(badHashing[0]);
// System.out.println("Getting with bad hashing:");
// System.out.println(badHashing[1]);
System.out.println("Inserting with id hashing:");
System.out.println(withId[0]);
System.out.println("Getting with id hashing:");
System.out.println(withId[1]);
System.out.println("Inserting with id and name hashing:");
System.out.println(withIdAndName[0]);
System.out.println("Getting with id and name hashing:");
System.out.println(withIdAndName[1]);
System.out.println("Inserting with Objects hashing:");
System.out.println(withObjects[0]);
System.out.println("Getting with Objects hashing:");
System.out.println(withObjects[1]);
}
private String randomName() {
return names[random.nextInt(2)];
}
private <T extends Member> Duration[] testDuration(Supplier<T> factory) {
HashMap<T, String> map = new HashMap<>();
Stopwatch stopwatch = Stopwatch.createUnstarted();
stopwatch.start();
for(int i = 0; i < SAMPLES; i++) {
T member = factory.get();
member.id = i;
member.name = randomName();
map.put(member, member.name);
}
stopwatch.stop();
Duration elapsedInserting = stopwatch.elapsed();
stopwatch.reset();
stopwatch.start();
for (T key : map.keySet()) {
map.get(key);
}
stopwatch.stop();
Duration elapsedGetting = stopwatch.elapsed();
stopwatch.reset();
return new Duration[]{elapsedInserting, elapsedGetting};
}
}

View File

@@ -0,0 +1,21 @@
package com.baeldung.map.identity;
import org.junit.jupiter.api.Test;
import java.util.IdentityHashMap;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class IdentityHashMapDemonstratorUnitTest {
@Test
public void givenIdentityHashMap_whenNewObjectWithSameKey_thenAddsAsNewValue() {
IdentityHashMap<String, String> identityHashMap = IdentityHashMapDemonstrator.createWithSimpleData();
String newGenreKey = new String("genre");
identityHashMap.put(newGenreKey, "Drama");
assertEquals(5, identityHashMap.size());
assertEquals("Fantasy", identityHashMap.get("genre"));
assertEquals("Drama", identityHashMap.get(newGenreKey));
}
}

View File

@@ -0,0 +1,72 @@
package com.baeldung.map.invert;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class InvertHashMapUnitTest {
Map<String, Integer> sourceMap;
@BeforeEach
void setup() {
sourceMap = new HashMap<>();
sourceMap.put("Sunday", 0);
sourceMap.put("Monday", 1);
sourceMap.put("Tuesday", 2);
sourceMap.put("Wednesday", 3);
sourceMap.put("Thursday", 4);
sourceMap.put("Friday", 5);
sourceMap.put("Saturday", 6);
}
@Test
void givenSourceMap_whenUsingForLoop_returnsInvertedMap() {
Map<Integer, String> inversedMap = InvertHashMapExample.invertMapUsingForLoop(sourceMap);
assertNotNull(inversedMap);
assertEquals(sourceMap.size(), inversedMap.size());
assertEquals("Monday", inversedMap.get(1));
}
@Test
void givenSourceMap_whenUsingStreams_returnsInvertedMap() {
Map<Integer, String> inversedMap = InvertHashMapExample.invertMapUsingStreams(sourceMap);
assertNotNull(inversedMap);
assertEquals(sourceMap.size(), inversedMap.size());
assertEquals("Monday", inversedMap.get(1));
}
@Test
void givenSourceMap_whenUsingMapper_returnsInvertedMap() {
Map<Integer, String> inversedMap = InvertHashMapExample.invertMapUsingMapper(sourceMap);
assertNotNull(inversedMap);
assertEquals(sourceMap.size(), inversedMap.size());
assertEquals("Monday", inversedMap.get(1));
}
@Test
void givenSourceMapWithDuplicateValues_whenUsingGroupBy_returnsInvertedMap() {
sourceMap.put("MONDAY", 1);
Map<Integer, List<String>> inversedMap = InvertHashMapExample.invertMapUsingGroupingBy(sourceMap);
assertNotNull(inversedMap);
assertNotEquals(sourceMap.size(), inversedMap.size()); // duplicate keys are merged now
assertEquals(2, inversedMap.get(1).size());
assertTrue(inversedMap.get(1).contains("Monday"));
assertTrue(inversedMap.get(1).contains("MONDAY"));
}
}

View File

@@ -0,0 +1,30 @@
package com.baeldung.map.keysetValuesEntrySet;
import org.junit.Test;
import java.util.AbstractMap.SimpleEntry;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class EntrySetExampleUnitTest {
@Test
public void givenHashMap_whenEntrySetApplied_thenShouldReturnSetOfEntries() {
Map<String, Integer> map = new HashMap<>();
map.put("one", 1);
map.put("two", 2);
Set<Map.Entry<String, Integer>> actualValues = map.entrySet();
assertEquals(2, actualValues.size());
assertTrue(actualValues.contains(new SimpleEntry<>("one", 1)));
assertTrue(actualValues.contains(new SimpleEntry<>("two", 2)));
}
}

View File

@@ -0,0 +1,27 @@
package com.baeldung.map.keysetValuesEntrySet;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class KeySetExampleUnitTest {
@Test
public void givenHashMap_whenKeySetApplied_thenShouldReturnSetOfKeys() {
Map<String, Integer> map = new HashMap<>();
map.put("one", 1);
map.put("two", 2);
Set<String> actualValues = map.keySet();
assertEquals(2, actualValues.size());
assertTrue(actualValues.contains("one"));
assertTrue(actualValues.contains("two"));
}
}

View File

@@ -0,0 +1,27 @@
package com.baeldung.map.keysetValuesEntrySet;
import org.junit.Test;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class ValuesExampleUnitTest {
@Test
public void givenHashMap_whenValuesApplied_thenShouldReturnCollectionOfValues() {
Map<String, Integer> map = new HashMap<>();
map.put("one", 1);
map.put("two", 2);
Collection<Integer> actualValues = map.values();
assertEquals(2, actualValues.size());
assertTrue(actualValues.contains(1));
assertTrue(actualValues.contains(2));
}
}