Merge branch 'eugenp:master' into PR-7091

This commit is contained in:
parthiv39731
2023-11-20 12:50:08 +05:30
committed by GitHub
132 changed files with 1844 additions and 166 deletions
+1 -1
View File
@@ -28,7 +28,7 @@
</modules>
<properties>
<commons-codec.version>1.11</commons-codec.version>
<commons-codec.version>1.16.0</commons-codec.version>
<commons-math3.version>3.6.1</commons-math3.version>
<cobertura.plugin.version>2.7</cobertura.plugin.version>
<tradukisto.version>1.0.1</tradukisto.version>
+1 -1
View File
@@ -234,7 +234,7 @@
<properties>
<!-- util -->
<commons-codec.version>1.10</commons-codec.version>
<commons-codec.version>1.16.0</commons-codec.version>
<httpasyncclient.version>4.1.5</httpasyncclient.version>
<!-- testing -->
<wiremock.version>2.5.1</wiremock.version>
+1
View File
@@ -14,3 +14,4 @@ You can build the project from the command line using: *mvn clean install*, or i
- [Get Partition Count for a Topic in Kafka](https://www.baeldung.com/java-kafka-partition-count-topic)
- [bootstrap-server in Kafka Configuration](https://www.baeldung.com/java-kafka-bootstrap-server)
- [Introduction to Apache Kafka](https://www.baeldung.com/apache-kafka)
- [Ensuring Message Ordering in Kafka: Strategies and Configurations](https://www.baeldung.com/kafka-message-ordering)
+1 -1
View File
@@ -75,7 +75,7 @@
<properties>
<gson.version>2.10.1</gson.version>
<dynamodblocal.version>1.21.1</dynamodblocal.version>
<commons-codec-version>1.10.L001</commons-codec-version>
<commons-codec-version>1.16.0</commons-codec-version>
<jets3t-version>0.9.4.0006L</jets3t-version>
<maven-plugins-version>3.1.1</maven-plugins-version>
</properties>
@@ -0,0 +1,47 @@
package com.baeldung.deserializationfilters;
import java.io.ObjectInputFilter;
import java.util.function.BinaryOperator;
import com.baeldung.deserializationfilters.service.DeserializationService;
import com.baeldung.deserializationfilters.service.LimitedArrayService;
import com.baeldung.deserializationfilters.service.LowDepthService;
import com.baeldung.deserializationfilters.service.SmallObjectService;
import com.baeldung.deserializationfilters.utils.FilterUtils;
public class ContextSpecificDeserializationFilterFactory implements BinaryOperator<ObjectInputFilter> {
@Override
public ObjectInputFilter apply(ObjectInputFilter current, ObjectInputFilter next) {
if (current == null) {
Class<?> caller = findInStack(DeserializationService.class);
if (caller == null) {
current = FilterUtils.fallbackFilter();
} else if (caller.equals(SmallObjectService.class)) {
current = FilterUtils.safeSizeFilter(190);
} else if (caller.equals(LowDepthService.class)) {
current = FilterUtils.safeDepthFilter(2);
} else if (caller.equals(LimitedArrayService.class)) {
current = FilterUtils.safeArrayFilter(3);
}
}
return ObjectInputFilter.merge(current, next);
}
private static Class<?> findInStack(Class<?> superType) {
for (StackTraceElement element : Thread.currentThread()
.getStackTrace()) {
try {
Class<?> subType = Class.forName(element.getClassName());
if (superType.isAssignableFrom(subType)) {
return subType;
}
} catch (ClassNotFoundException e) {
return null;
}
}
return null;
}
}
@@ -0,0 +1,7 @@
package com.baeldung.deserializationfilters.pojo;
import java.io.Serializable;
public interface ContextSpecific extends Serializable {
}
@@ -0,0 +1,19 @@
package com.baeldung.deserializationfilters.pojo;
public class NestedSample implements ContextSpecific {
private static final long serialVersionUID = 1L;
private Sample optional;
public NestedSample(Sample optional) {
this.optional = optional;
}
public Sample getOptional() {
return optional;
}
public void setOptional(Sample optional) {
this.optional = optional;
}
}
@@ -0,0 +1,61 @@
package com.baeldung.deserializationfilters.pojo;
public class Sample implements ContextSpecific, Comparable<Sample> {
private static final long serialVersionUID = 1L;
private int[] array;
private String name;
private NestedSample nested;
public Sample(String name) {
this.name = name;
}
public Sample(int[] array) {
this.array = array;
}
public Sample(NestedSample nested) {
this.nested = nested;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int[] getArray() {
return array;
}
public void setArray(int[] array) {
this.array = array;
}
public NestedSample getNested() {
return nested;
}
public void setNested(NestedSample nested) {
this.nested = nested;
}
@Override
public String toString() {
return name;
}
@Override
public int compareTo(Sample o) {
if (name == null)
return -1;
if (o == null || o.getName() == null)
return 1;
return getName().compareTo(o.getName());
}
}
@@ -0,0 +1,25 @@
package com.baeldung.deserializationfilters.pojo;
public class SampleExploit extends Sample {
private static final long serialVersionUID = 1L;
public SampleExploit() {
super("exploit");
}
public static void maliciousCode() {
System.out.println("exploit executed");
}
@Override
public String toString() {
maliciousCode();
return "exploit";
}
@Override
public int compareTo(Sample o) {
maliciousCode();
return super.compareTo(o);
}
}
@@ -0,0 +1,11 @@
package com.baeldung.deserializationfilters.service;
import java.io.InputStream;
import java.util.Set;
import com.baeldung.deserializationfilters.pojo.ContextSpecific;
public interface DeserializationService {
Set<ContextSpecific> process(InputStream... inputStreams);
}
@@ -0,0 +1,15 @@
package com.baeldung.deserializationfilters.service;
import java.io.InputStream;
import java.util.Set;
import com.baeldung.deserializationfilters.pojo.ContextSpecific;
import com.baeldung.deserializationfilters.utils.DeserializationUtils;
public class LimitedArrayService implements DeserializationService {
@Override
public Set<ContextSpecific> process(InputStream... inputStreams) {
return DeserializationUtils.deserializeIntoSet(inputStreams);
}
}
@@ -0,0 +1,20 @@
package com.baeldung.deserializationfilters.service;
import java.io.InputStream;
import java.io.ObjectInputFilter;
import java.util.Set;
import com.baeldung.deserializationfilters.pojo.ContextSpecific;
import com.baeldung.deserializationfilters.utils.DeserializationUtils;
public class LowDepthService implements DeserializationService {
public Set<ContextSpecific> process(ObjectInputFilter filter, InputStream... inputStreams) {
return DeserializationUtils.deserializeIntoSet(filter, inputStreams);
}
@Override
public Set<ContextSpecific> process(InputStream... inputStreams) {
return process(null, inputStreams);
}
}
@@ -0,0 +1,15 @@
package com.baeldung.deserializationfilters.service;
import java.io.InputStream;
import java.util.Set;
import com.baeldung.deserializationfilters.pojo.ContextSpecific;
import com.baeldung.deserializationfilters.utils.DeserializationUtils;
public class SmallObjectService implements DeserializationService {
@Override
public Set<ContextSpecific> process(InputStream... inputStreams) {
return DeserializationUtils.deserializeIntoSet(inputStreams);
}
}
@@ -0,0 +1,50 @@
package com.baeldung.deserializationfilters.utils;
import java.io.InputStream;
import java.io.InvalidClassException;
import java.io.ObjectInputFilter;
import java.io.ObjectInputStream;
import java.util.Set;
import java.util.TreeSet;
import com.baeldung.deserializationfilters.pojo.ContextSpecific;
public class DeserializationUtils {
private DeserializationUtils() {
}
public static Object deserialize(InputStream inStream) {
return deserialize(inStream, null);
}
public static Object deserialize(InputStream inStream, ObjectInputFilter filter) {
try (ObjectInputStream in = new ObjectInputStream(inStream)) {
if (filter != null) {
in.setObjectInputFilter(filter);
}
return in.readObject();
} catch (InvalidClassException e) {
return null;
} catch (Throwable e) {
e.printStackTrace();
return null;
}
}
public static Set<ContextSpecific> deserializeIntoSet(InputStream... inputStreams) {
return deserializeIntoSet(null, inputStreams);
}
public static Set<ContextSpecific> deserializeIntoSet(ObjectInputFilter filter, InputStream... inputStreams) {
Set<ContextSpecific> set = new TreeSet<>();
for (InputStream inputStream : inputStreams) {
Object object = deserialize(inputStream, filter);
if (object != null) {
set.add((ContextSpecific) object);
}
}
return set;
}
}
@@ -0,0 +1,32 @@
package com.baeldung.deserializationfilters.utils;
import java.io.ObjectInputFilter;
public class FilterUtils {
private static final String DEFAULT_PACKAGE_PATTERN = "java.base/*;!*";
private static final String POJO_PACKAGE = "com.baeldung.deserializationfilters.pojo";
private FilterUtils() {
}
private static ObjectInputFilter baseFilter(String parameter, int max) {
return ObjectInputFilter.Config.createFilter(String.format("%s=%d;%s.**;%s", parameter, max, POJO_PACKAGE, DEFAULT_PACKAGE_PATTERN));
}
public static ObjectInputFilter fallbackFilter() {
return ObjectInputFilter.Config.createFilter(String.format("%s", DEFAULT_PACKAGE_PATTERN));
}
public static ObjectInputFilter safeSizeFilter(int max) {
return baseFilter("maxbytes", max);
}
public static ObjectInputFilter safeArrayFilter(int max) {
return baseFilter("maxarray", max);
}
public static ObjectInputFilter safeDepthFilter(int max) {
return baseFilter("maxdepth", max);
}
}
@@ -0,0 +1,17 @@
package com.baeldung.deserializationfilters.utils;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
public class SerializationUtils {
private SerializationUtils() {
}
public static void serialize(Object object, OutputStream outStream) throws IOException {
try (ObjectOutputStream objStream = new ObjectOutputStream(outStream)) {
objStream.writeObject(object);
}
}
}
@@ -0,0 +1,119 @@
package com.baeldung.deserializationfilters;
import static org.junit.Assert.assertNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputFilter;
import java.util.Set;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import com.baeldung.deserializationfilters.pojo.ContextSpecific;
import com.baeldung.deserializationfilters.pojo.NestedSample;
import com.baeldung.deserializationfilters.pojo.Sample;
import com.baeldung.deserializationfilters.pojo.SampleExploit;
import com.baeldung.deserializationfilters.service.LimitedArrayService;
import com.baeldung.deserializationfilters.service.LowDepthService;
import com.baeldung.deserializationfilters.service.SmallObjectService;
import com.baeldung.deserializationfilters.utils.DeserializationUtils;
import com.baeldung.deserializationfilters.utils.FilterUtils;
import com.baeldung.deserializationfilters.utils.SerializationUtils;
public class ContextSpecificDeserializationFilterIntegrationTest {
private static ByteArrayOutputStream serialSampleA = new ByteArrayOutputStream();
private static ByteArrayOutputStream serialBigSampleA = new ByteArrayOutputStream();
private static ByteArrayOutputStream serialSampleB = new ByteArrayOutputStream();
private static ByteArrayOutputStream serialBigSampleB = new ByteArrayOutputStream();
private static ByteArrayOutputStream serialSampleC = new ByteArrayOutputStream();
private static ByteArrayOutputStream serialBigSampleC = new ByteArrayOutputStream();
private static ByteArrayInputStream bytes(ByteArrayOutputStream stream) {
return new ByteArrayInputStream(stream.toByteArray());
}
@BeforeAll
static void setup() throws IOException {
ObjectInputFilter.Config.setSerialFilterFactory(new ContextSpecificDeserializationFilterFactory());
SerializationUtils.serialize(new Sample("simple"), serialSampleA);
SerializationUtils.serialize(new SampleExploit(), serialBigSampleA);
SerializationUtils.serialize(new Sample(new int[] { 1, 2, 3 }), serialSampleB);
SerializationUtils.serialize(new Sample(new int[] { 1, 2, 3, 4, 5, 6 }), serialBigSampleB);
SerializationUtils.serialize(new Sample(new NestedSample(null)), serialSampleC);
SerializationUtils.serialize(new Sample(new NestedSample(new Sample("deep"))), serialBigSampleC);
}
@Test
void whenSmallObjectContext_thenCorrectFilterApplied() {
Set<ContextSpecific> result = new SmallObjectService().process( //
bytes(serialSampleA), //
bytes(serialBigSampleA));
assertEquals(1, result.size());
assertEquals("simple", ((Sample) result.iterator()
.next()).getName());
}
@Test
void whenLimitedArrayContext_thenCorrectFilterApplied() {
Set<ContextSpecific> result = new LimitedArrayService().process( //
bytes(serialSampleB), //
bytes(serialBigSampleB));
assertEquals(1, result.size());
}
@Test
void whenLowDepthContext_thenCorrectFilterApplied() {
Set<ContextSpecific> result = new LowDepthService().process( //
bytes(serialSampleC), //
bytes(serialBigSampleC));
assertEquals(1, result.size());
}
@Test
void givenExtraFilter_whenCombinedContext_thenMergedFiltersApplied() {
Set<ContextSpecific> result = new LowDepthService().process( //
FilterUtils.safeSizeFilter(190), //
bytes(serialSampleA), //
bytes(serialBigSampleA), //
bytes(serialSampleC), //
bytes(serialBigSampleC));
assertEquals(1, result.size());
assertEquals("simple", ((Sample) result.iterator()
.next()).getName());
}
@Test
void givenFallbackContext_whenUsingBaseClasses_thenRestrictiveFilterApplied() throws IOException {
String a = new String("a");
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
SerializationUtils.serialize(a, outStream);
String deserializedA = (String) DeserializationUtils.deserialize(bytes(outStream));
assertEquals(a, deserializedA);
}
@Test
void givenFallbackContext_whenUsingAppClasses_thenRejected() throws IOException {
Sample a = new Sample("a");
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
SerializationUtils.serialize(a, outStream);
Sample deserializedA = (Sample) DeserializationUtils.deserialize(bytes(outStream));
assertNull(deserializedA);
}
}
@@ -18,19 +18,19 @@ public class VehicleUnitTest {
}
@Test
public void givenCar_whenUsingReflectionAPI_thenSuperClassIsSealed() {
public void givenCar_whenUsingReflectionAPI_thenSuperClassIsSealed() throws ClassNotFoundException {
Assertions.assertThat(car.getClass().isSealed()).isEqualTo(false);
Assertions.assertThat(car.getClass().getSuperclass().isSealed()).isEqualTo(true);
Assertions.assertThat(car.getClass().getSuperclass().getPermittedSubclasses())
.contains(ClassDesc.of(car.getClass().getCanonicalName()));
.contains(Class.forName(car.getClass().getCanonicalName()));
}
@Test
public void givenTruck_whenUsingReflectionAPI_thenSuperClassIsSealed() {
public void givenTruck_whenUsingReflectionAPI_thenSuperClassIsSealed() throws ClassNotFoundException {
Assertions.assertThat(truck.getClass().isSealed()).isEqualTo(false);
Assertions.assertThat(truck.getClass().getSuperclass().isSealed()).isEqualTo(true);
Assertions.assertThat(truck.getClass().getSuperclass().getPermittedSubclasses())
.contains(ClassDesc.of(truck.getClass().getCanonicalName()));
.contains(Class.forName(truck.getClass().getCanonicalName()));
}
@Test
@@ -18,19 +18,19 @@ public class VehicleUnitTest {
}
@Test
public void givenCar_whenUsingReflectionAPI_thenInterfaceIsSealed() {
public void givenCar_whenUsingReflectionAPI_thenInterfaceIsSealed() throws ClassNotFoundException {
Assertions.assertThat(car.getClass().isSealed()).isEqualTo(false);
Assertions.assertThat(car.getClass().getInterfaces()[0].isSealed()).isEqualTo(true);
Assertions.assertThat(car.getClass().getInterfaces()[0].permittedSubclasses())
.contains(ClassDesc.of(car.getClass().getCanonicalName()));
Assertions.assertThat(car.getClass().getInterfaces()[0].getPermittedSubclasses())
.contains(Class.forName(car.getClass().getCanonicalName()));
}
@Test
public void givenTruck_whenUsingReflectionAPI_thenInterfaceIsSealed() {
public void givenTruck_whenUsingReflectionAPI_thenInterfaceIsSealed() throws ClassNotFoundException {
Assertions.assertThat(truck.getClass().isSealed()).isEqualTo(false);
Assertions.assertThat(truck.getClass().getInterfaces()[0].isSealed()).isEqualTo(true);
Assertions.assertThat(truck.getClass().getInterfaces()[0].permittedSubclasses())
.contains(ClassDesc.of(truck.getClass().getCanonicalName()));
Assertions.assertThat(truck.getClass().getInterfaces()[0].getPermittedSubclasses())
.contains(Class.forName(truck.getClass().getCanonicalName()));
}
@Test
@@ -7,4 +7,5 @@
- [Difference Between Instant and LocalDateTime](https://www.baeldung.com/java-instant-vs-localdatetime)
- [Add Minutes to a Time String in Java](https://www.baeldung.com/java-string-time-add-mins)
- [Round the Date in Java](https://www.baeldung.com/java-round-the-date)
- [Representing Furthest Possible Date in Java](https://www.baeldung.com/java-date-represent-max)
- [[<-- Prev]](/core-java-modules/core-java-datetime-java8-1)
@@ -34,7 +34,6 @@
<properties>
<commons-lang.version>2.2</commons-lang.version>
<commons-lang3.version>3.12.0</commons-lang3.version>
</properties>
</project>
@@ -9,4 +9,5 @@
- [Skipping the First Iteration in Java](https://www.baeldung.com/java-skip-first-iteration)
- [Remove Elements From a Queue Using Loop](https://www.baeldung.com/java-remove-elements-queue)
- [Intro to Vector Class in Java](https://www.baeldung.com/java-vector-guide)
- [HashSet toArray() Method in Java](https://www.baeldung.com/java-hashset-toarray)
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-4)
@@ -0,0 +1,60 @@
package com.baeldung.collectionssortcomplexity;
import org.openjdk.jmh.annotations.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Fork(value = 1, warmups = 1)
@Warmup(iterations = 5, time = 1)
@Measurement(iterations = 5, time = 1)
public class CollectionsSortTimeComplexityJMH {
public static void main(String[] args) throws Exception {
org.openjdk.jmh.Main.main(args);
}
@Benchmark
public void measureCollectionsSortBestCase(BestCaseBenchmarkState state) {
List<Integer> sortedList = new ArrayList<>(state.sortedList);
Collections.sort(sortedList);
}
@Benchmark
public void measureCollectionsSortAverageWorstCase(AverageWorstCaseBenchmarkState state) {
List<Integer> unsortedList = new ArrayList<>(state.unsortedList);
Collections.sort(unsortedList);
}
@State(Scope.Benchmark)
public static class BestCaseBenchmarkState {
List<Integer> sortedList;
@Setup(Level.Trial)
public void setUp() {
sortedList = new ArrayList<>();
for (int i = 1; i <= 1000000; i++) {
sortedList.add(i);
}
}
}
@State(Scope.Benchmark)
public static class AverageWorstCaseBenchmarkState {
List<Integer> unsortedList;
@Setup(Level.Trial)
public void setUp() {
unsortedList = new ArrayList<>();
for (int i = 1000000; i > 0; i--) {
unsortedList.add(i);
}
}
}
}
@@ -0,0 +1,33 @@
package com.baeldung.collectionssortcomplexity;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class CollectionsSortTimeComplexityMain {
// O(n log n) Time Complexity Example
public static void worstAndAverageCasesTimeComplexity() {
Integer[] sortedArray = {20, 21, 22, 23, 24, 25, 26, 17, 28, 29, 30, 31, 18, 19, 32, 33, 34, 27, 35};
List<Integer> list = Arrays.asList(sortedArray);
Collections.shuffle(list);
long startTime = System.nanoTime();
Collections.sort(list);
long endTime = System.nanoTime();
System.out.println("Execution Time for O(n log n): " + (endTime - startTime) + " nanoseconds");
}
// O(n) Time Complexity Example
public static void bestCaseTimeComplexity() {
Integer[] sortedArray = {19, 22, 19, 22, 24, 25, 17, 11, 22, 23, 28, 23, 0, 1, 12, 9, 13, 27, 15};
List<Integer> list = Arrays.asList(sortedArray);
long startTime = System.nanoTime();
Collections.sort(list);
long endTime = System.nanoTime();
System.out.println("Execution Time for O(n): " + (endTime - startTime) + " nanoseconds");
}
public static void main(String[] args) {
worstAndAverageCasesTimeComplexity();
bestCaseTimeComplexity();
}
}
@@ -66,7 +66,6 @@
<properties>
<jmh.version>1.21</jmh.version>
<commons-lang.version>2.2</commons-lang.version>
<commons-lang3.version>3.12.0</commons-lang3.version>
<gson.version>2.10.1</gson.version>
<jackson.version>2.15.2</jackson.version>
<org.json.version>20230618</org.json.version>
@@ -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]));
}
}
@@ -12,4 +12,5 @@ This module contains articles about basic Java concurrency.
- [CompletableFuture allOf().join() vs. CompletableFuture.join()](https://www.baeldung.com/java-completablefuture-allof-join)
- [Retry Logic with CompletableFuture](https://www.baeldung.com/java-completablefuture-retry-logic)
- [Convert From List of CompletableFuture to CompletableFuture List](https://www.baeldung.com/java-completablefuture-list-convert)
- [Synchronize a Static Variable Among Different Threads](https://www.baeldung.com/java-synchronize-static-variable-different-threads)
- [[<-- Prev]](../core-java-concurrency-basic-2)

Some files were not shown because too many files have changed in this diff Show More