[BAEL-6787] increment value of a map (#15243)
Co-authored-by: Bhaskar <bhaskar.dastidar@freshworks.com>
This commit is contained in:
parent
3371e4fe53
commit
684a14ce5f
@ -33,6 +33,11 @@
|
||||
<artifactId>commons-csv</artifactId>
|
||||
<version>${csv.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>32.1.2-jre</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
@ -0,0 +1,70 @@
|
||||
package com.baeldung.map;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class BenchmarkMapMethods {
|
||||
public static void main(String[] args) {
|
||||
BenchmarkMapMethods bmm = new BenchmarkMapMethods();
|
||||
Map<String, Long> map = new HashMap<>();
|
||||
map.put("Guava", bmm.benchMarkGuavaMap());
|
||||
map.put("ContainsKey", bmm.benchContainsKeyMap());
|
||||
map.put("MergeMethod", bmm.benchMarkMergeMethod());
|
||||
map.put("ComputeMethod", bmm.benchMarComputeMethod());
|
||||
map.put("GetOrDefault", bmm.benchMarkGetOrDefaultMethod());
|
||||
}
|
||||
|
||||
private long benchMarkGuavaMap() {
|
||||
long startTime = System.nanoTime();
|
||||
IncrementMapValueWays im = new IncrementMapValueWays();
|
||||
im.charFrequencyUsingAtomicMap(getString());
|
||||
long endTime = System.nanoTime();
|
||||
return endTime - startTime;
|
||||
}
|
||||
|
||||
private long benchContainsKeyMap() {
|
||||
long startTime = System.nanoTime();
|
||||
IncrementMapValueWays im = new IncrementMapValueWays();
|
||||
im.charFrequencyUsingContainsKey(getString());
|
||||
long endTime = System.nanoTime();
|
||||
return endTime - startTime;
|
||||
}
|
||||
|
||||
private long benchMarComputeMethod() {
|
||||
long startTime = System.nanoTime();
|
||||
IncrementMapValueWays im = new IncrementMapValueWays();
|
||||
im.charFrequencyUsingCompute(getString());
|
||||
long endTime = System.nanoTime();
|
||||
return endTime - startTime;
|
||||
}
|
||||
|
||||
private long benchMarkMergeMethod() {
|
||||
long startTime = System.nanoTime();
|
||||
IncrementMapValueWays im = new IncrementMapValueWays();
|
||||
im.charFrequencyUsingMerge(getString());
|
||||
long endTime = System.nanoTime();
|
||||
return endTime - startTime;
|
||||
}
|
||||
|
||||
private long benchMarkGetOrDefaultMethod() {
|
||||
long startTime = System.nanoTime();
|
||||
IncrementMapValueWays im = new IncrementMapValueWays();
|
||||
im.charFrequencyUsingGetOrDefault(getString());
|
||||
long endTime = System.nanoTime();
|
||||
return endTime - startTime;
|
||||
}
|
||||
|
||||
private String getString() {
|
||||
return
|
||||
"Once upon a time in a quaint village nestled between rolling hills and whispering forests, there lived a solitary storyteller named Elias. Elias was known for spinning tales that transported listeners to magical realms and awakened forgotten dreams.\n"
|
||||
+ "\n"
|
||||
+ "His favorite spot was beneath an ancient oak tree, its sprawling branches offering shade to those who sought refuge from the bustle of daily life. Villagers of all ages would gather around Elias, their faces illuminated by the warmth of his stories.\n"
|
||||
+ "\n" + "One evening, as dusk painted the sky in hues of orange and purple, a curious young girl named Lily approached Elias. Her eyes sparkled with wonder as she asked for a tale unlike any other.\n" + "\n"
|
||||
+ "Elias smiled, sensing her thirst for adventure, and began a story about a forgotten kingdom veiled by mist, guarded by mystical creatures and enchanted by ancient spells. With each word, the air grew thick with anticipation, and the listeners were transported into a world where magic danced on the edges of reality.\n"
|
||||
+ "\n" + "As Elias weaved the story, Lily's imagination took flight. She envisioned herself as a brave warrior, wielding a shimmering sword against dark forces, her heart fueled by courage and kindness.\n" + "\n"
|
||||
+ "The night wore on, but the spell of the tale held everyone captive. The villagers laughed, gasped, and held their breaths, journeying alongside the characters through trials and triumphs.\n" + "\n"
|
||||
+ "As the final words lingered in the air, a sense of enchantment settled upon the listeners. They thanked Elias for the gift of his storytelling, each carrying a piece of the magical kingdom within their hearts.\n" + "\n"
|
||||
+ "Lily, inspired by the story, vowed to cherish the spirit of adventure and kindness in her own life. With a newfound spark in her eyes, she bid Elias goodnight, already dreaming of the countless adventures awaiting her.\n" + "\n"
|
||||
+ "Under the star-studded sky, Elias remained beneath the ancient oak, his heart aglow with the joy of sharing tales that ignited imagination and inspired dreams. And as the night embraced the village, whispers of the enchanted kingdom lingered in the breeze, promising endless possibilities to those who dared to believe.";
|
||||
}
|
||||
}
|
@ -0,0 +1,80 @@
|
||||
package com.baeldung.map;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import com.google.common.util.concurrent.AtomicLongMap;
|
||||
|
||||
public class IncrementMapValueWays {
|
||||
|
||||
public Map<Character, Integer> charFrequencyUsingContainsKey(String sentence) {
|
||||
Map<Character, Integer> charMap = new HashMap<>();
|
||||
for (int c = 0; c < sentence.length(); c++) {
|
||||
int count = 0;
|
||||
if (charMap.containsKey(sentence.charAt(c))) {
|
||||
count = charMap.get(sentence.charAt(c));
|
||||
}
|
||||
charMap.put(sentence.charAt(c), count + 1);
|
||||
}
|
||||
return charMap;
|
||||
}
|
||||
|
||||
public Map<Character, Integer> charFrequencyUsingGetOrDefault(String sentence) {
|
||||
Map<Character, Integer> charMap = new HashMap<>();
|
||||
for (int c = 0; c < sentence.length(); c++) {
|
||||
charMap.put(sentence.charAt(c), charMap.getOrDefault(sentence.charAt(c), 0) + 1);
|
||||
}
|
||||
return charMap;
|
||||
}
|
||||
|
||||
public Map<Character, Integer> charFrequencyUsingMerge(String sentence) {
|
||||
Map<Character, Integer> charMap = new HashMap<>();
|
||||
for (int c = 0; c < sentence.length(); c++) {
|
||||
charMap.merge(sentence.charAt(c), 1, Integer::sum);
|
||||
}
|
||||
return charMap;
|
||||
}
|
||||
|
||||
public Map<Character, Integer> charFrequencyUsingCompute(String sentence) {
|
||||
Map<Character, Integer> charMap = new HashMap<>();
|
||||
for (int c = 0; c < sentence.length(); c++) {
|
||||
charMap.compute(sentence.charAt(c), (key, value) -> (value == null) ? 1 : value + 1);
|
||||
}
|
||||
return charMap;
|
||||
}
|
||||
|
||||
public Map<Character, Long> charFrequencyUsingAtomicMap(String sentence) {
|
||||
AtomicLongMap<Character> map = AtomicLongMap.create();
|
||||
for (int c = 0; c < sentence.length(); c++) {
|
||||
map.getAndIncrement(sentence.charAt(c));
|
||||
}
|
||||
return map.asMap();
|
||||
}
|
||||
|
||||
public Map<Character, Integer> charFrequencyWithConcurrentMap(String sentence, Map<Character, Integer> charMap) {
|
||||
for (int c = 0; c < sentence.length(); c++) {
|
||||
charMap.compute(sentence.charAt(c), (key, value) -> (value == null) ? 1 : value + 1);
|
||||
}
|
||||
return charMap;
|
||||
}
|
||||
|
||||
public Map<Character, AtomicInteger> charFrequencyWithGetAndIncrement(String sentence) {
|
||||
Map<Character, AtomicInteger> charMap = new HashMap<>();
|
||||
for (int c = 0; c < sentence.length(); c++) {
|
||||
charMap.putIfAbsent(sentence.charAt(c), new AtomicInteger(0));
|
||||
charMap.get(sentence.charAt(c))
|
||||
.incrementAndGet();
|
||||
}
|
||||
return charMap;
|
||||
}
|
||||
|
||||
public Map<Character, AtomicInteger> charFrequencyWithGetAndIncrementComputeIfAbsent(String sentence) {
|
||||
Map<Character, AtomicInteger> charMap = new HashMap<>();
|
||||
for (int c = 0; c < sentence.length(); c++) {
|
||||
charMap.computeIfAbsent(sentence.charAt(c), k -> new AtomicInteger(0))
|
||||
.incrementAndGet();
|
||||
}
|
||||
return charMap;
|
||||
}
|
||||
}
|
@ -0,0 +1,103 @@
|
||||
package com.baeldung.map;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class IncrementMapValueUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenString_whenUsingContainsKey_thenReturnFreqMap() {
|
||||
String string = "the quick brown fox jumps over the lazy dog";
|
||||
IncrementMapValueWays ic = new IncrementMapValueWays();
|
||||
Map<Character, Integer> actualMap = ic.charFrequencyUsingContainsKey(string);
|
||||
Map<Character, Integer> expectedMap = getExpectedMap();
|
||||
Assert.assertEquals(expectedMap, actualMap);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenUsingGetOrDefault_thenReturnFreqMap() {
|
||||
String string = "the quick brown fox jumps over the lazy dog";
|
||||
IncrementMapValueWays ic = new IncrementMapValueWays();
|
||||
Map<Character, Integer> actualMap = ic.charFrequencyUsingGetOrDefault(string);
|
||||
Map<Character, Integer> expectedMap = getExpectedMap();
|
||||
Assert.assertEquals(expectedMap, actualMap);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenUsingMapMerge_thenReturnFreqMap() {
|
||||
String string = "the quick brown fox jumps over the lazy dog";
|
||||
IncrementMapValueWays ic = new IncrementMapValueWays();
|
||||
Map<Character, Integer> actualMap = ic.charFrequencyUsingMerge(string);
|
||||
Map<Character, Integer> expectedMap = getExpectedMap();
|
||||
Assert.assertEquals(expectedMap, actualMap);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenUsingMapCompute_thenReturnFreqMap() {
|
||||
String string = "the quick brown fox jumps over the lazy dog";
|
||||
IncrementMapValueWays ic = new IncrementMapValueWays();
|
||||
Map<Character, Integer> actualMap = ic.charFrequencyUsingCompute(string);
|
||||
Map<Character, Integer> expectedMap = getExpectedMap();
|
||||
Assert.assertEquals(expectedMap, actualMap);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenUsingGuava_thenReturnFreqMap() {
|
||||
String string = "the quick brown fox jumps over the lazy dog";
|
||||
IncrementMapValueWays ic = new IncrementMapValueWays();
|
||||
Map<Character, Long> actualMap = ic.charFrequencyUsingAtomicMap(string);
|
||||
Map<Character, Integer> expectedMap = getExpectedMap();
|
||||
Assert.assertEquals(expectedMap.keySet(), actualMap.keySet());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenUsingIncrementAndGet_thenReturnFreqMap() {
|
||||
String string = "the quick brown fox jumps over the lazy dog";
|
||||
IncrementMapValueWays ic = new IncrementMapValueWays();
|
||||
Map<Character, AtomicInteger> actualMap = ic.charFrequencyWithGetAndIncrement(string);
|
||||
Assert.assertEquals(getExpectedMap().keySet(), actualMap.keySet());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenUsingIncrementAndGetAndComputeIfAbsent_thenReturnFreqMap() {
|
||||
String string = "the quick brown fox jumps over the lazy dog";
|
||||
IncrementMapValueWays ic = new IncrementMapValueWays();
|
||||
Map<Character, AtomicInteger> actualMap = ic.charFrequencyWithGetAndIncrementComputeIfAbsent(string);
|
||||
Assert.assertEquals(getExpectedMap().keySet(), actualMap.keySet());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenUsingConcurrentMapCompute_thenReturnFreqMap() throws InterruptedException {
|
||||
Map<Character, Integer> charMap = new ConcurrentHashMap<>();
|
||||
Thread thread1 = new Thread(() -> {
|
||||
IncrementMapValueWays ic = new IncrementMapValueWays();
|
||||
ic.charFrequencyWithConcurrentMap("the quick brown", charMap);
|
||||
});
|
||||
|
||||
Thread thread2 = new Thread(() -> {
|
||||
IncrementMapValueWays ic = new IncrementMapValueWays();
|
||||
ic.charFrequencyWithConcurrentMap(" fox jumps over the lazy dog", charMap);
|
||||
});
|
||||
|
||||
thread1.start();
|
||||
thread2.start();
|
||||
thread1.join();
|
||||
thread2.join();
|
||||
|
||||
Map<Character, Integer> expectedMap = getExpectedMap();
|
||||
Assert.assertEquals(expectedMap, charMap);
|
||||
}
|
||||
|
||||
private Map<Character, Integer> getExpectedMap() {
|
||||
return Stream.of(
|
||||
new Object[][] { { ' ', 8 }, { 'a', 1 }, { 'b', 1 }, { 'c', 1 }, { 'd', 1 }, { 'e', 3 }, { 'f', 1 }, { 'g', 1 }, { 'h', 2 }, { 'i', 1 }, { 'j', 1 }, { 'k', 1 }, { 'l', 1 }, { 'm', 1 }, { 'n', 1 }, { 'o', 4 }, { 'p', 1 }, { 'q', 1 }, { 'r', 2 },
|
||||
{ 's', 1 }, { 't', 2 }, { 'u', 2 }, { 'v', 1 }, { 'w', 1 }, { 'x', 1 }, { 'y', 1 }, { 'z', 1 } })
|
||||
.collect(Collectors.toMap(data -> (Character) data[0], data -> (Integer) data[1]));
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user