Merge remote-tracking branch 'upstream/master' into feature/BAEL-7062-GetIndex

This commit is contained in:
Niket Agrawal
2023-10-07 23:25:36 +05:30
28 changed files with 967 additions and 13 deletions
@@ -0,0 +1 @@
## Relevant Articles
@@ -0,0 +1,78 @@
<?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-7</artifactId>
<name>core-java-collections-maps-7</name>
<packaging>jar</packaging>
<parent>
<artifactId>core-java-modules</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<properties>
<spring.version>5.2.5.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.4</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>1.36</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.9</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20230227</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,60 @@
package com.baeldung.map;
import java.util.HashMap;
import java.util.Map;
public class ConvertHashMapStringToHashMapObjectUsingtoString {
public String name;
public int age;
public ConvertHashMapStringToHashMapObjectUsingtoString(String name, int age) {
this.name = name;
this.age = age;
}
public static ConvertHashMapStringToHashMapObjectUsingtoString deserializeCustomObject(String valueString) {
if (valueString.startsWith("{") && valueString.endsWith("}")) {
valueString = valueString.substring(1, valueString.length() - 1);
String[] parts = valueString.split(",");
String name = null;
int age = -1;
for (String part : parts) {
String[] keyValue = part.split("=");
if (keyValue.length == 2) {
String key = keyValue[0].trim();
String val = keyValue[1].trim();
if (key.equals("name")) {
name = val;
} else if (key.equals("age")) {
age = Integer.parseInt(val);
}
}
}
if (name != null && age >= 0) {
return new ConvertHashMapStringToHashMapObjectUsingtoString(name, age);
}
}
return new ConvertHashMapStringToHashMapObjectUsingtoString("", -1);
}
public static void main(String[] args) {
String hashMapString = "{key1={name=John, age=30}, key2={name=Alice, age=25}}";
String keyValuePairs = hashMapString.replaceAll("[{}\\s]", "");
String[] pairs = keyValuePairs.split(",");
Map<String, ConvertHashMapStringToHashMapObjectUsingtoString> actualHashMap = new HashMap<>();
for (String pair : pairs) {
String[] keyValue = pair.split("=");
if (keyValue.length == 2) {
String key = keyValue[0];
ConvertHashMapStringToHashMapObjectUsingtoString value = deserializeCustomObject(keyValue[1]);
actualHashMap.put(key, value);
}
}
System.out.println(actualHashMap);
}
@Override
public String toString() {
return "{name=" + name + ", age=" + age + "}";
}
}
@@ -0,0 +1,31 @@
package com.baeldung.map;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class ConvertHashMapStringToHashMapObjectUsingtoStringUnitTest {
@Test
void givenValidCustomObject_whenSerializing_thenSerializedStringIsCorrect() {
ConvertHashMapStringToHashMapObjectUsingtoString customObject = new ConvertHashMapStringToHashMapObjectUsingtoString("John", 30);
String expectedSerializedString = "{name=John, age=30}";
assertEquals(expectedSerializedString, customObject.toString());
}
@Test
void givenValidSerializedString_whenDeserializing_thenCustomObjectIsCorrect() {
String serializedString = "{name=Alice, age=25}";
ConvertHashMapStringToHashMapObjectUsingtoString customObject = ConvertHashMapStringToHashMapObjectUsingtoString.deserializeCustomObject(serializedString);
assertEquals("Alice", customObject.name);
assertEquals(25, customObject.age);
}
@Test
void givenInvalidSerializedString_whenDeserializing_thenDefaultCustomObjectIsCreated() {
String invalidSerializedString = "{invalidString}";
ConvertHashMapStringToHashMapObjectUsingtoString customObject = ConvertHashMapStringToHashMapObjectUsingtoString.deserializeCustomObject(invalidSerializedString);
assertEquals("", customObject.name);
assertEquals(-1, customObject.age);
}
}
+4 -13
View File
@@ -44,19 +44,9 @@
<version>${vavr.version}</version>
</dependency>
<dependency>
<groupId>com.codepoetics</groupId>
<artifactId>protonpack</artifactId>
<version>1.16</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
<dependency>
<groupId>one.util</groupId>
<artifactId>streamex</artifactId>
<version>0.8.1</version>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
</dependencies>
@@ -87,6 +77,7 @@
<maven.compiler.source>12</maven.compiler.source>
<maven.compiler.target>12</maven.compiler.target>
<vavr.version>0.10.2</vavr.version>
<guava.version>32.1.2-jre</guava.version>
</properties>
</project>
@@ -0,0 +1,90 @@
package com.baeldung.streams.partitioning;
import java.util.ArrayList;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import com.google.common.collect.Iterables;
public class PartitionStream {
public static <T> Stream<List<T>> partitionList(List<T> source, int batchSize) {
if (batchSize <= 0) {
throw new IllegalArgumentException(String.format("Expected the batchSize to be greater than ZERO, actual value was: %s", batchSize));
}
if (source.isEmpty()) {
return Stream.empty();
}
int nrOfFullBatches = (source.size() - 1) / batchSize;
return IntStream.rangeClosed(0, nrOfFullBatches)
.mapToObj(batch -> {
int startIndex = batch * batchSize;
int endIndex = (batch == nrOfFullBatches) ? source.size() : (batch + 1) * batchSize;
return source.subList(startIndex, endIndex);
});
}
public static <T> Iterable<List<T>> partitionUsingGuava(Stream<T> source, int batchSize) {
return Iterables.partition(source::iterator, batchSize);
}
public static <T> List<List<T>> partitionStream(Stream<T> source, int batchSize) {
return source.collect(partitionBySize(batchSize, Collectors.toList()));
}
public static <T, A, R> Collector<T, ?, R> partitionBySize(int batchSize, Collector<List<T>, A, R> downstream) {
Supplier<Accumulator<T, A>> supplier = () -> new Accumulator<>(
batchSize,
downstream.supplier().get(),
downstream.accumulator()::accept
);
BiConsumer<Accumulator<T, A>, T> accumulator = (acc, value) -> acc.add(value);
BinaryOperator<Accumulator<T, A>> combiner = (acc1, acc2) -> acc1.combine(acc2, downstream.combiner());
Function<Accumulator<T, A>, R> finisher = acc -> {
if (!acc.values.isEmpty()) {
downstream.accumulator().accept(acc.downstreamAccumulator, acc.values);
}
return downstream.finisher().apply(acc.downstreamAccumulator);
};
return Collector.of(supplier, accumulator, combiner, finisher, Collector.Characteristics.UNORDERED);
}
static class Accumulator<T, A> {
private final List<T> values = new ArrayList<>();
private final int batchSize;
private A downstreamAccumulator;
private final BiConsumer<A, List<T>> batchFullListener;
Accumulator(int batchSize, A accumulator, BiConsumer<A, List<T>> onBatchFull) {
this.batchSize = batchSize;
this.downstreamAccumulator = accumulator;
this.batchFullListener = onBatchFull;
}
void add(T value) {
values.add(value);
if (values.size() == batchSize) {
batchFullListener.accept(downstreamAccumulator, new ArrayList<>(values));
values.clear();
}
}
Accumulator<T, A> combine(Accumulator<T, A> other, BinaryOperator<A> accumulatorCombiner) {
this.downstreamAccumulator = accumulatorCombiner.apply(downstreamAccumulator, other.downstreamAccumulator);
other.values.forEach(this::add);
return this;
}
}
}
@@ -0,0 +1,82 @@
package com.baeldung.partitioning;
import static com.baeldung.streams.partitioning.PartitionStream.partitionList;
import static com.baeldung.streams.partitioning.PartitionStream.partitionStream;
import static com.baeldung.streams.partitioning.PartitionStream.partitionUsingGuava;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.atIndex;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
public class PartitionStreamsUnitTest {
@Test
void whenPartitionList_thenReturnThreeSubLists() {
List<Integer> source = List.of(1, 2, 3, 4, 5, 6, 7, 8);
Stream<List<Integer>> result = partitionList(source, 3);
assertThat(result)
.containsExactlyInAnyOrder(
List.of(1, 2, 3),
List.of(4, 5, 6),
List.of(7, 8)
);
}
@Test
void whenPartitionEmptyList_thenReturnEmptyStream() {
Stream<List<Integer>> result = partitionList(Collections.emptyList(), 3);
assertThat(result).isEmpty();
}
@Test
void whenPartitionListWithNegativeBatchSize_thenThrowException() {
assertThatThrownBy(() -> partitionList(List.of(1,2,3), -1))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Expected the batchSize to be greater than ZERO, actual value was: -1");
}
@Test
void whenPartitionParallelStream_thenReturnThreeSubLists() {
Stream<Integer> source = Stream.of(1, 2, 3, 4, 5, 6, 7, 8).parallel();
List<List<Integer>> result = partitionStream(source, 3);
assertThat(result)
.hasSize(3)
.satisfies(batch -> assertThat(batch).hasSize(3), atIndex(0))
.satisfies(batch -> assertThat(batch).hasSize(3), atIndex(1))
.satisfies(batch -> assertThat(batch).hasSize(2), atIndex(2));
}
@Test
void whenPartitionEmptyParallelStream_thenReturnEmptyList() {
Stream<Integer> source = Stream.<Integer>empty().parallel();
List<List<Integer>> result = partitionStream(source, 3);
assertThat(result).isEmpty();
}
@Test
void whenPartitionParallelStreamWithGuava_thenReturnThreeSubLists() {
Stream<Integer> source = Stream.of(1, 2, 3, 4, 5, 6, 7, 8).parallel();
Iterable<List<Integer>> result = partitionUsingGuava(source, 3);
assertThat(result)
.map(ArrayList::new)
.hasSize(3)
.satisfies(batch -> assertThat(batch).asList().hasSize(3), atIndex(0))
.satisfies(batch -> assertThat(batch).asList().hasSize(3), atIndex(1))
.satisfies(batch -> assertThat(batch).asList().hasSize(2), atIndex(2));
}
}