Merge remote-tracking branch 'upstream/master' into feature/BAEL-6695-BooleanValidation
This commit is contained in:
commit
8999b501c9
algorithms-modules/algorithms-miscellaneous-7/src
main/java/com/baeldung/algorithms/rotatearray
test/java/com/baeldung/algorithms/rotatearray
aws-modules
aws-dynamodb
.gitignoreREADME.mdpom.xml
src
main
java/com/baeldung/dynamodb
resources
test
java/com/baeldung/dynamodb
resources
aws-miscellaneous
pom.xmlcore-java-modules
core-java-11-2
core-java-16
core-java-17/src/test/java/com/baeldung/recordproperties
core-java-18
README.mdpom.xml
src
main
java/com/baeldung/finalization_closeable_cleaner
FinalizationExamples.javaMyCleanerResourceClass.javaMyCloseableResourceClass.javaMyFinalizableResourceClass.java
resources
test/java/com/baeldung/finalization_closeable_cleaner
core-java-arrays-convert
core-java-httpclient/src/main/java/com/baeldung/httpclient
core-java-io-5/src/test
java/com/baeldung/rmlinebreaks
resources
core-java-lang-oop-others/src
main/java/com/baeldung/encapsulation
test/java/com/baeldung/encapsulation
core-java-networking/src/test/java/com/baeldung/networking/url
core-java-numbers-3/src/test/java/com/baeldung/integerToBinary
core-java-numbers-6
README.md
src/test/java/com/baeldung/javadoublevsbigdecimal
core-java-numbers-conversions/src/test/java/com/baeldung
floatdoubleconversions
floattobigdecimal
core-java-reflection-3
README.mdpom.xml
src
main/java/com/baeldung/reflection/disadvantages
encapsulation
performance
test/java/com/baeldung/reflection/disadvantages/encapsulation
core-java-security/src/main/java/com/baeldung/ssl
core-java-streams-2
core-java-streams-3
core-java-streams-5
core-java-streams-simple
README.mdpom.xml
src
main
java/com/baeldung/streams
filter
groupingby
parallel
BenchmarkRunner.javaDifferentSourceSplitting.javaFileSearchCost.javaMemoryLocalityCosts.javaMergingCosts.javaParallelStream.javaSequentialStream.javaSplittingCosts.java
reduce
application
benchmarks
entities
utilities
resources
test/java/com/baeldung/streams
core-java-streams
102
algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/rotatearray/RotateArray.java
Normal file
102
algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/rotatearray/RotateArray.java
Normal file
@ -0,0 +1,102 @@
|
|||||||
|
package com.baeldung.algorithms.rotatearray;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* To speed up the rotation, we narrow k rotations to the remainder of k divided by the array length, or k module the array length.
|
||||||
|
* Therefore, a large rotation number will be translated into the relative smallest rotation.
|
||||||
|
* All solutions replace the original array, although they might use an extra array to compute the rotation.
|
||||||
|
*/
|
||||||
|
public class RotateArray {
|
||||||
|
|
||||||
|
private RotateArray() {
|
||||||
|
throw new IllegalStateException("Rotate array algorithm utility methods class");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* @param arr array to apply rotation to
|
||||||
|
* @param k number of rotations
|
||||||
|
*/
|
||||||
|
public static void bruteForce(int[] arr, int k) {
|
||||||
|
checkInvalidInput(arr, k);
|
||||||
|
|
||||||
|
k %= arr.length;
|
||||||
|
int temp;
|
||||||
|
int previous;
|
||||||
|
for (int i = 0; i < k; i++) {
|
||||||
|
previous = arr[arr.length - 1];
|
||||||
|
for (int j = 0; j < arr.length; j++) {
|
||||||
|
temp = arr[j];
|
||||||
|
arr[j] = previous;
|
||||||
|
previous = temp;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* @param arr array to apply rotation to
|
||||||
|
* @param k number of rotations
|
||||||
|
*/
|
||||||
|
public static void withExtraArray(int[] arr, int k) {
|
||||||
|
checkInvalidInput(arr, k);
|
||||||
|
|
||||||
|
int[] extraArray = new int[arr.length];
|
||||||
|
for (int i = 0; i < arr.length; i++) {
|
||||||
|
extraArray[(i + k) % arr.length] = arr[i];
|
||||||
|
}
|
||||||
|
System.arraycopy(extraArray, 0, arr, 0, arr.length);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* @param arr array to apply rotation to
|
||||||
|
* @param k number of rotations
|
||||||
|
*/
|
||||||
|
public static void cyclicReplacement(int[] arr, int k) {
|
||||||
|
checkInvalidInput(arr, k);
|
||||||
|
|
||||||
|
k = k % arr.length;
|
||||||
|
int count = 0;
|
||||||
|
for (int start = 0; count < arr.length; start++) {
|
||||||
|
int current = start;
|
||||||
|
int prev = arr[start];
|
||||||
|
do {
|
||||||
|
int next = (current + k) % arr.length;
|
||||||
|
int temp = arr[next];
|
||||||
|
arr[next] = prev;
|
||||||
|
prev = temp;
|
||||||
|
current = next;
|
||||||
|
count++;
|
||||||
|
} while (start != current);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* @param arr array to apply rotation to
|
||||||
|
* @param k number of rotations
|
||||||
|
*/
|
||||||
|
public static void reverse(int[] arr, int k) {
|
||||||
|
checkInvalidInput(arr, k);
|
||||||
|
|
||||||
|
k %= arr.length;
|
||||||
|
reverse(arr, 0, arr.length - 1);
|
||||||
|
reverse(arr, 0, k - 1);
|
||||||
|
reverse(arr, k, arr.length - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void reverse(int[] nums, int start, int end) {
|
||||||
|
while (start < end) {
|
||||||
|
int temp = nums[start];
|
||||||
|
nums[start] = nums[end];
|
||||||
|
nums[end] = temp;
|
||||||
|
start++;
|
||||||
|
end--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void checkInvalidInput(int[] arr, int rotation) {
|
||||||
|
if (rotation < 1 || arr == null)
|
||||||
|
throw new IllegalArgumentException("Rotation must be greater than zero or array must be not null");
|
||||||
|
}
|
||||||
|
}
|
124
algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/rotatearray/RotateArrayUnitTest.java
Normal file
124
algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/rotatearray/RotateArrayUnitTest.java
Normal file
@ -0,0 +1,124 @@
|
|||||||
|
package com.baeldung.algorithms.rotatearray;
|
||||||
|
|
||||||
|
import static com.baeldung.algorithms.rotatearray.RotateArray.bruteForce;
|
||||||
|
import static com.baeldung.algorithms.rotatearray.RotateArray.cyclicReplacement;
|
||||||
|
import static com.baeldung.algorithms.rotatearray.RotateArray.reverse;
|
||||||
|
import static com.baeldung.algorithms.rotatearray.RotateArray.withExtraArray;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
class RotateArrayUnitTest {
|
||||||
|
|
||||||
|
private final int[] arr = { 1, 2, 3, 4, 5, 6 };
|
||||||
|
private final int rotationLtArrayLength = 1;
|
||||||
|
private final int rotationGtArrayLength = arr.length + 2;
|
||||||
|
private final int[] ltArrayLengthRotation = { 6, 1, 2, 3, 4, 5 };
|
||||||
|
private final int[] gtArrayLengthRotation = { 5, 6, 1, 2, 3, 4 };
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenInputArray_whenNoRotationOrEmptyArray_thenThrowIllegalArgumentException() {
|
||||||
|
final int noRotation = 0;
|
||||||
|
final int someRotation = arr.length - 1;
|
||||||
|
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> bruteForce(arr, noRotation));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> withExtraArray(arr, noRotation));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> cyclicReplacement(arr, noRotation));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> reverse(arr, noRotation));
|
||||||
|
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> bruteForce(null, someRotation));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> withExtraArray(null, someRotation));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> cyclicReplacement(null, someRotation));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> reverse(null, someRotation));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenInputArray_whenUseBruteForceRotationLtArrayLength_thenRotateArrayOk() {
|
||||||
|
|
||||||
|
bruteForce(arr, rotationLtArrayLength);
|
||||||
|
assertArrayEquals(ltArrayLengthRotation, arr);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenInputArray_whenUseBruteForceRotationGtArrayLength_thenRotateArrayOk() {
|
||||||
|
|
||||||
|
bruteForce(arr, rotationGtArrayLength);
|
||||||
|
assertArrayEquals(gtArrayLengthRotation, arr);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenInputArray_whenUseBruteForceRotationEqArrayLength_thenDoNothing() {
|
||||||
|
int[] expected = arr.clone();
|
||||||
|
|
||||||
|
bruteForce(arr, arr.length);
|
||||||
|
assertArrayEquals(expected, arr);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenInputArray_whenUseExtraArrayRotationLtArrayLength_thenRotateArrayOk() {
|
||||||
|
|
||||||
|
withExtraArray(arr, rotationLtArrayLength);
|
||||||
|
assertArrayEquals(ltArrayLengthRotation, arr);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenInputArray_whenUseExtraArrayRotationGtArrayLength_thenRotateArrayOk() {
|
||||||
|
|
||||||
|
withExtraArray(arr, rotationGtArrayLength);
|
||||||
|
assertArrayEquals(gtArrayLengthRotation, arr);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenInputArray_whenUseExtraArrayWithRotationEqArrayLength_thenDoNothing() {
|
||||||
|
int[] clone = arr.clone();
|
||||||
|
|
||||||
|
withExtraArray(arr, arr.length);
|
||||||
|
assertArrayEquals(clone, arr);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenInputArray_whenUseCyclicReplacementRotationLtArrayLength_thenRotateArrayOk() {
|
||||||
|
|
||||||
|
cyclicReplacement(arr, rotationLtArrayLength);
|
||||||
|
assertArrayEquals(ltArrayLengthRotation, arr);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenInputArray_whenUseCyclicReplacementRotationGtArrayLength_thenRotateArrayOk() {
|
||||||
|
|
||||||
|
cyclicReplacement(arr, rotationGtArrayLength);
|
||||||
|
assertArrayEquals(gtArrayLengthRotation, arr);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenInputArray_whenUseCyclicReplacementRotationEqArrayLength_thenDoNothing() {
|
||||||
|
int[] clone = arr.clone();
|
||||||
|
|
||||||
|
cyclicReplacement(arr, arr.length);
|
||||||
|
assertArrayEquals(clone, arr);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenInputArray_whenUseReverseRotationLtArrayLength_thenRotateArrayOk() {
|
||||||
|
|
||||||
|
reverse(arr, rotationLtArrayLength);
|
||||||
|
assertArrayEquals(ltArrayLengthRotation, arr);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenInputArray_whenUseReverseRotationGtArrayLength_thenRotateArrayOk() {
|
||||||
|
|
||||||
|
reverse(arr, rotationGtArrayLength);
|
||||||
|
assertArrayEquals(gtArrayLengthRotation, arr);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenInputArray_whenUseReverseRotationEqArrayLength_thenDoNothing() {
|
||||||
|
|
||||||
|
int[] clone = arr.clone();
|
||||||
|
|
||||||
|
reverse(arr, arr.length);
|
||||||
|
assertArrayEquals(clone, arr);
|
||||||
|
}
|
||||||
|
}
|
2
aws-modules/aws-dynamodb/.gitignore
vendored
Normal file
2
aws-modules/aws-dynamodb/.gitignore
vendored
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
/target/
|
||||||
|
.idea/
|
7
aws-modules/aws-dynamodb/README.md
Normal file
7
aws-modules/aws-dynamodb/README.md
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
## AWS DYNAMODB
|
||||||
|
|
||||||
|
This module contains articles about AWS DynamoDB
|
||||||
|
|
||||||
|
### Relevant articles
|
||||||
|
- [Integration Testing with a Local DynamoDB Instance](https://www.baeldung.com/dynamodb-local-integration-tests)
|
||||||
|
|
87
aws-modules/aws-dynamodb/pom.xml
Normal file
87
aws-modules/aws-dynamodb/pom.xml
Normal file
@ -0,0 +1,87 @@
|
|||||||
|
<?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>aws-dynamodb</artifactId>
|
||||||
|
<version>0.1.0-SNAPSHOT</version>
|
||||||
|
<name>aws-dynamodb</name>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>aws-modules</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.amazonaws</groupId>
|
||||||
|
<artifactId>aws-java-sdk</artifactId>
|
||||||
|
<version>${aws-java-sdk.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.amazonaws</groupId>
|
||||||
|
<artifactId>DynamoDBLocal</artifactId>
|
||||||
|
<version>${dynamodblocal.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>commons-io</groupId>
|
||||||
|
<artifactId>commons-io</artifactId>
|
||||||
|
<version>${commons-io.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.google.code.gson</groupId>
|
||||||
|
<artifactId>gson</artifactId>
|
||||||
|
<version>${gson.version}</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-shade-plugin</artifactId>
|
||||||
|
<version>${maven-shade-plugin.version}</version>
|
||||||
|
<configuration>
|
||||||
|
<createDependencyReducedPom>false</createDependencyReducedPom>
|
||||||
|
</configuration>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<phase>package</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>shade</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-dependency-plugin</artifactId>
|
||||||
|
<version>${maven-plugins-version}</version>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<id>copy</id>
|
||||||
|
<phase>compile</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>copy-dependencies</goal>
|
||||||
|
</goals>
|
||||||
|
<configuration>
|
||||||
|
<includeScope></includeScope>
|
||||||
|
<includeTypes>so,dll,dylib</includeTypes>
|
||||||
|
<outputDirectory>native-libs</outputDirectory>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<gson.version>2.8.0</gson.version>
|
||||||
|
<dynamodblocal.version>1.21.1</dynamodblocal.version>
|
||||||
|
<maven-plugins-version>3.1.1</maven-plugins-version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
</project>
|
13
aws-modules/aws-dynamodb/src/main/resources/logback.xml
Normal file
13
aws-modules/aws-dynamodb/src/main/resources/logback.xml
Normal 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>
|
@ -49,10 +49,10 @@ public class ProductInfoRepositoryIntegrationTest {
|
|||||||
@BeforeClass
|
@BeforeClass
|
||||||
public static void setupClass() {
|
public static void setupClass() {
|
||||||
Properties testProperties = loadFromFileInClasspath("test.properties")
|
Properties testProperties = loadFromFileInClasspath("test.properties")
|
||||||
.filter(properties -> !isEmpty(properties.getProperty(AWS_ACCESSKEY)))
|
.filter(properties -> !isEmpty(properties.getProperty(AWS_ACCESSKEY)))
|
||||||
.filter(properties -> !isEmpty(properties.getProperty(AWS_SECRETKEY)))
|
.filter(properties -> !isEmpty(properties.getProperty(AWS_SECRETKEY)))
|
||||||
.filter(properties -> !isEmpty(properties.getProperty(DYNAMODB_ENDPOINT)))
|
.filter(properties -> !isEmpty(properties.getProperty(DYNAMODB_ENDPOINT)))
|
||||||
.orElseThrow(() -> new RuntimeException("Unable to get all of the required test property values"));
|
.orElseThrow(() -> new RuntimeException("Unable to get all of the required test property values"));
|
||||||
|
|
||||||
String amazonAWSAccessKey = testProperties.getProperty(AWS_ACCESSKEY);
|
String amazonAWSAccessKey = testProperties.getProperty(AWS_ACCESSKEY);
|
||||||
String amazonAWSSecretKey = testProperties.getProperty(AWS_SECRETKEY);
|
String amazonAWSSecretKey = testProperties.getProperty(AWS_SECRETKEY);
|
@ -16,31 +16,9 @@
|
|||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.amazonaws</groupId>
|
<groupId>software.amazon.awssdk</groupId>
|
||||||
<artifactId>aws-java-sdk</artifactId>
|
<artifactId>aws-sdk-java</artifactId>
|
||||||
<version>${aws-java-sdk.version}</version>
|
<version>${aws-java-sdk-v2.version}</version>
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.amazonaws</groupId>
|
|
||||||
<artifactId>aws-lambda-java-core</artifactId>
|
|
||||||
<version>${aws-lambda-java-core.version}</version>
|
|
||||||
<exclusions>
|
|
||||||
<exclusion>
|
|
||||||
<artifactId>commons-logging</artifactId>
|
|
||||||
<groupId>commons-logging</groupId>
|
|
||||||
</exclusion>
|
|
||||||
</exclusions>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.amazonaws</groupId>
|
|
||||||
<artifactId>aws-lambda-java-events</artifactId>
|
|
||||||
<version>${aws-lambda-java-events.version}</version>
|
|
||||||
<exclusions>
|
|
||||||
<exclusion>
|
|
||||||
<artifactId>commons-logging</artifactId>
|
|
||||||
<groupId>commons-logging</groupId>
|
|
||||||
</exclusion>
|
|
||||||
</exclusions>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>commons-io</groupId>
|
<groupId>commons-io</groupId>
|
||||||
@ -52,12 +30,6 @@
|
|||||||
<artifactId>gson</artifactId>
|
<artifactId>gson</artifactId>
|
||||||
<version>${gson.version}</version>
|
<version>${gson.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
|
||||||
<groupId>com.amazonaws</groupId>
|
|
||||||
<artifactId>DynamoDBLocal</artifactId>
|
|
||||||
<version>${dynamodblocal.version}</version>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
@ -101,8 +73,6 @@
|
|||||||
</build>
|
</build>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<aws-lambda-java-events.version>1.3.0</aws-lambda-java-events.version>
|
|
||||||
<aws-lambda-java-core.version>1.1.0</aws-lambda-java-core.version>
|
|
||||||
<gson.version>2.8.0</gson.version>
|
<gson.version>2.8.0</gson.version>
|
||||||
<dynamodblocal.version>1.21.1</dynamodblocal.version>
|
<dynamodblocal.version>1.21.1</dynamodblocal.version>
|
||||||
<commons-codec-version>1.10.L001</commons-codec-version>
|
<commons-codec-version>1.10.L001</commons-codec-version>
|
||||||
|
@ -2,136 +2,148 @@ package com.baeldung.ec2;
|
|||||||
|
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
|
|
||||||
import com.amazonaws.auth.AWSCredentials;
|
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
|
||||||
import com.amazonaws.auth.AWSStaticCredentialsProvider;
|
import software.amazon.awssdk.regions.Region;
|
||||||
import com.amazonaws.auth.BasicAWSCredentials;
|
import software.amazon.awssdk.services.ec2.Ec2Client;
|
||||||
import com.amazonaws.regions.Regions;
|
import software.amazon.awssdk.services.ec2.model.AuthorizeSecurityGroupIngressRequest;
|
||||||
import com.amazonaws.services.ec2.AmazonEC2;
|
import software.amazon.awssdk.services.ec2.model.CreateKeyPairRequest;
|
||||||
import com.amazonaws.services.ec2.AmazonEC2ClientBuilder;
|
import software.amazon.awssdk.services.ec2.model.CreateKeyPairResponse;
|
||||||
import com.amazonaws.services.ec2.model.AuthorizeSecurityGroupIngressRequest;
|
import software.amazon.awssdk.services.ec2.model.CreateSecurityGroupRequest;
|
||||||
import com.amazonaws.services.ec2.model.CreateKeyPairRequest;
|
import software.amazon.awssdk.services.ec2.model.DescribeInstancesRequest;
|
||||||
import com.amazonaws.services.ec2.model.CreateKeyPairResult;
|
import software.amazon.awssdk.services.ec2.model.DescribeInstancesResponse;
|
||||||
import com.amazonaws.services.ec2.model.CreateSecurityGroupRequest;
|
import software.amazon.awssdk.services.ec2.model.DescribeKeyPairsRequest;
|
||||||
import com.amazonaws.services.ec2.model.DescribeInstancesRequest;
|
import software.amazon.awssdk.services.ec2.model.DescribeKeyPairsResponse;
|
||||||
import com.amazonaws.services.ec2.model.DescribeInstancesResult;
|
import software.amazon.awssdk.services.ec2.model.IpPermission;
|
||||||
import com.amazonaws.services.ec2.model.DescribeKeyPairsRequest;
|
import software.amazon.awssdk.services.ec2.model.IpRange;
|
||||||
import com.amazonaws.services.ec2.model.DescribeKeyPairsResult;
|
import software.amazon.awssdk.services.ec2.model.MonitorInstancesRequest;
|
||||||
import com.amazonaws.services.ec2.model.IpPermission;
|
import software.amazon.awssdk.services.ec2.model.RebootInstancesRequest;
|
||||||
import com.amazonaws.services.ec2.model.IpRange;
|
import software.amazon.awssdk.services.ec2.model.RunInstancesRequest;
|
||||||
import com.amazonaws.services.ec2.model.MonitorInstancesRequest;
|
import software.amazon.awssdk.services.ec2.model.RunInstancesResponse;
|
||||||
import com.amazonaws.services.ec2.model.RebootInstancesRequest;
|
import software.amazon.awssdk.services.ec2.model.StartInstancesRequest;
|
||||||
import com.amazonaws.services.ec2.model.RunInstancesRequest;
|
import software.amazon.awssdk.services.ec2.model.StartInstancesResponse;
|
||||||
import com.amazonaws.services.ec2.model.StartInstancesRequest;
|
import software.amazon.awssdk.services.ec2.model.StopInstancesRequest;
|
||||||
import com.amazonaws.services.ec2.model.StopInstancesRequest;
|
import software.amazon.awssdk.services.ec2.model.UnmonitorInstancesRequest;
|
||||||
import com.amazonaws.services.ec2.model.UnmonitorInstancesRequest;
|
|
||||||
|
|
||||||
public class EC2Application {
|
public class EC2Application {
|
||||||
|
|
||||||
private static final AWSCredentials credentials;
|
|
||||||
|
|
||||||
static {
|
|
||||||
// put your accesskey and secretkey here
|
|
||||||
credentials = new BasicAWSCredentials(
|
|
||||||
"<AWS accesskey>",
|
|
||||||
"<AWS secretkey>"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
|
|
||||||
// Set up the client
|
// Set up the client
|
||||||
AmazonEC2 ec2Client = AmazonEC2ClientBuilder.standard()
|
Ec2Client ec2Client = Ec2Client.builder()
|
||||||
.withCredentials(new AWSStaticCredentialsProvider(credentials))
|
.credentialsProvider(ProfileCredentialsProvider.create("default"))
|
||||||
.withRegion(Regions.US_EAST_1)
|
.region(Region.US_EAST_1)
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
// Create a security group
|
// Create a security group
|
||||||
CreateSecurityGroupRequest createSecurityGroupRequest = new CreateSecurityGroupRequest().withGroupName("BaeldungSecurityGroup")
|
CreateSecurityGroupRequest createSecurityGroupRequest = CreateSecurityGroupRequest.builder()
|
||||||
.withDescription("Baeldung Security Group");
|
.groupName("BaeldungSecurityGroup")
|
||||||
|
.description("Baeldung Security Group")
|
||||||
|
.build();
|
||||||
|
|
||||||
ec2Client.createSecurityGroup(createSecurityGroupRequest);
|
ec2Client.createSecurityGroup(createSecurityGroupRequest);
|
||||||
|
|
||||||
// Allow HTTP and SSH traffic
|
// Allow HTTP and SSH traffic
|
||||||
IpRange ipRange1 = new IpRange().withCidrIp("0.0.0.0/0");
|
IpRange ipRange1 = IpRange.builder()
|
||||||
|
.cidrIp("0.0.0.0/0")
|
||||||
|
.build();
|
||||||
|
|
||||||
IpPermission ipPermission1 = new IpPermission().withIpv4Ranges(Arrays.asList(new IpRange[] { ipRange1 }))
|
IpPermission ipPermission1 = IpPermission.builder()
|
||||||
.withIpProtocol("tcp")
|
.ipRanges(Arrays.asList(ipRange1))
|
||||||
.withFromPort(80)
|
.ipProtocol("tcp")
|
||||||
.withToPort(80);
|
.fromPort(80)
|
||||||
|
.toPort(80)
|
||||||
|
.build();
|
||||||
|
|
||||||
IpPermission ipPermission2 = new IpPermission().withIpv4Ranges(Arrays.asList(new IpRange[] { ipRange1 }))
|
IpPermission ipPermission2 = IpPermission.builder()
|
||||||
.withIpProtocol("tcp")
|
.ipRanges(Arrays.asList(ipRange1))
|
||||||
.withFromPort(22)
|
.ipProtocol("tcp")
|
||||||
.withToPort(22);
|
.fromPort(22)
|
||||||
|
.toPort(22)
|
||||||
|
.build();
|
||||||
|
|
||||||
AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest()
|
AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = AuthorizeSecurityGroupIngressRequest
|
||||||
.withGroupName("BaeldungSecurityGroup")
|
.builder()
|
||||||
.withIpPermissions(ipPermission1, ipPermission2);
|
.groupName("BaeldungSecurityGroup")
|
||||||
|
.ipPermissions(ipPermission1, ipPermission2)
|
||||||
|
.build();
|
||||||
|
|
||||||
ec2Client.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest);
|
ec2Client.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest);
|
||||||
|
|
||||||
// Create KeyPair
|
// Create KeyPair
|
||||||
CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest()
|
CreateKeyPairRequest createKeyPairRequest = CreateKeyPairRequest.builder()
|
||||||
.withKeyName("baeldung-key-pair");
|
.keyName("baeldung-key-pair")
|
||||||
CreateKeyPairResult createKeyPairResult = ec2Client.createKeyPair(createKeyPairRequest);
|
.build();
|
||||||
String privateKey = createKeyPairResult
|
|
||||||
.getKeyPair()
|
CreateKeyPairResponse createKeyPairResponse = ec2Client.createKeyPair(createKeyPairRequest);
|
||||||
.getKeyMaterial(); // make sure you keep it, the private key, Amazon doesn't store the private key
|
String privateKey = createKeyPairResponse.keyMaterial();
|
||||||
|
// make sure you keep it, the private key, Amazon doesn't store the private key
|
||||||
|
|
||||||
// See what key-pairs you've got
|
// See what key-pairs you've got
|
||||||
DescribeKeyPairsRequest describeKeyPairsRequest = new DescribeKeyPairsRequest();
|
DescribeKeyPairsRequest describeKeyPairsRequest = DescribeKeyPairsRequest.builder()
|
||||||
DescribeKeyPairsResult describeKeyPairsResult = ec2Client.describeKeyPairs(describeKeyPairsRequest);
|
.build();
|
||||||
|
DescribeKeyPairsResponse describeKeyPairsResponse = ec2Client.describeKeyPairs(describeKeyPairsRequest);
|
||||||
|
|
||||||
// Launch an Amazon Instance
|
// Launch an Amazon Instance
|
||||||
RunInstancesRequest runInstancesRequest = new RunInstancesRequest().withImageId("ami-97785bed") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html | https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/usingsharedamis-finding.html
|
RunInstancesRequest runInstancesRequest = RunInstancesRequest.builder()
|
||||||
.withInstanceType("t2.micro") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html
|
.imageId("ami-97785bed")
|
||||||
.withMinCount(1)
|
.instanceType("t2.micro") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html
|
||||||
.withMaxCount(1)
|
.minCount(1)
|
||||||
.withKeyName("baeldung-key-pair") // optional - if not present, can't connect to instance
|
.maxCount(1)
|
||||||
.withSecurityGroups("BaeldungSecurityGroup");
|
.keyName("baeldung-key-pair") // optional - if not present, can't connect to instance
|
||||||
|
.securityGroups("BaeldungSecurityGroup")
|
||||||
|
.build();
|
||||||
|
|
||||||
String yourInstanceId = ec2Client.runInstances(runInstancesRequest).getReservation().getInstances().get(0).getInstanceId();
|
RunInstancesResponse runInstancesResponse = ec2Client.runInstances(runInstancesRequest);
|
||||||
|
String yourInstanceId = runInstancesResponse.instances().get(0).instanceId();
|
||||||
|
|
||||||
// Start an Instance
|
// Start an Instance
|
||||||
StartInstancesRequest startInstancesRequest = new StartInstancesRequest()
|
StartInstancesRequest startInstancesRequest = StartInstancesRequest.builder()
|
||||||
.withInstanceIds(yourInstanceId);
|
.instanceIds(yourInstanceId)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
StartInstancesResponse startInstancesResponse = ec2Client.startInstances(startInstancesRequest);
|
||||||
|
|
||||||
ec2Client.startInstances(startInstancesRequest);
|
|
||||||
|
|
||||||
// Monitor Instances
|
// Monitor Instances
|
||||||
MonitorInstancesRequest monitorInstancesRequest = new MonitorInstancesRequest()
|
MonitorInstancesRequest monitorInstancesRequest = MonitorInstancesRequest.builder()
|
||||||
.withInstanceIds(yourInstanceId);
|
.instanceIds(yourInstanceId)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
|
||||||
ec2Client.monitorInstances(monitorInstancesRequest);
|
ec2Client.monitorInstances(monitorInstancesRequest);
|
||||||
|
|
||||||
UnmonitorInstancesRequest unmonitorInstancesRequest = new UnmonitorInstancesRequest()
|
UnmonitorInstancesRequest unmonitorInstancesRequest = UnmonitorInstancesRequest.builder()
|
||||||
.withInstanceIds(yourInstanceId);
|
.instanceIds(yourInstanceId)
|
||||||
|
.build();
|
||||||
|
|
||||||
ec2Client.unmonitorInstances(unmonitorInstancesRequest);
|
ec2Client.unmonitorInstances(unmonitorInstancesRequest);
|
||||||
|
|
||||||
// Reboot an Instance
|
// Reboot an Instance
|
||||||
|
RebootInstancesRequest rebootInstancesRequest = RebootInstancesRequest.builder()
|
||||||
RebootInstancesRequest rebootInstancesRequest = new RebootInstancesRequest()
|
.instanceIds(yourInstanceId)
|
||||||
.withInstanceIds(yourInstanceId);
|
.build();
|
||||||
|
|
||||||
ec2Client.rebootInstances(rebootInstancesRequest);
|
ec2Client.rebootInstances(rebootInstancesRequest);
|
||||||
|
|
||||||
// Stop an Instance
|
// Stop an Instance
|
||||||
StopInstancesRequest stopInstancesRequest = new StopInstancesRequest()
|
StopInstancesRequest stopInstancesRequest = StopInstancesRequest.builder()
|
||||||
.withInstanceIds(yourInstanceId);
|
.instanceIds(yourInstanceId)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
|
||||||
ec2Client.stopInstances(stopInstancesRequest)
|
ec2Client.stopInstances(stopInstancesRequest)
|
||||||
.getStoppingInstances()
|
.stoppingInstances()
|
||||||
.get(0)
|
.get(0)
|
||||||
.getPreviousState()
|
.previousState()
|
||||||
.getName();
|
.name();
|
||||||
|
|
||||||
// Describe an Instance
|
// Describe an Instance
|
||||||
DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest();
|
DescribeInstancesRequest describeInstancesRequest = DescribeInstancesRequest.builder().build();
|
||||||
DescribeInstancesResult response = ec2Client.describeInstances(describeInstancesRequest);
|
DescribeInstancesResponse response = ec2Client.describeInstances(describeInstancesRequest);
|
||||||
System.out.println(response.getReservations()
|
System.out.println(response.reservations()
|
||||||
.get(0)
|
.get(0)
|
||||||
.getInstances()
|
.instances()
|
||||||
.get(0)
|
.get(0)
|
||||||
.getKernelId());
|
.kernelId());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,13 +1,5 @@
|
|||||||
package com.baeldung.rds;
|
package com.baeldung.rds;
|
||||||
|
|
||||||
import com.amazonaws.auth.AWSCredentialsProvider;
|
|
||||||
import com.amazonaws.auth.AWSStaticCredentialsProvider;
|
|
||||||
import com.amazonaws.auth.BasicAWSCredentials;
|
|
||||||
import com.amazonaws.regions.Regions;
|
|
||||||
import com.amazonaws.services.rds.AmazonRDS;
|
|
||||||
import com.amazonaws.services.rds.AmazonRDSClientBuilder;
|
|
||||||
import com.amazonaws.services.rds.model.*;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
import java.sql.*;
|
import java.sql.*;
|
||||||
@ -16,12 +8,22 @@ import java.util.Properties;
|
|||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
import java.util.logging.Logger;
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
|
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
|
||||||
|
import software.amazon.awssdk.regions.Region;
|
||||||
|
import software.amazon.awssdk.services.rds.RdsClient;
|
||||||
|
import software.amazon.awssdk.services.rds.model.CreateDbInstanceRequest;
|
||||||
|
import software.amazon.awssdk.services.rds.model.CreateDbInstanceResponse;
|
||||||
|
import software.amazon.awssdk.services.rds.model.DBInstance;
|
||||||
|
import software.amazon.awssdk.services.rds.model.DeleteDbInstanceRequest;
|
||||||
|
import software.amazon.awssdk.services.rds.model.DeleteDbInstanceResponse;
|
||||||
|
import software.amazon.awssdk.services.rds.model.DescribeDbInstancesResponse;
|
||||||
|
import software.amazon.awssdk.services.rds.model.Endpoint;
|
||||||
|
|
||||||
public class AWSRDSService {
|
public class AWSRDSService {
|
||||||
|
|
||||||
|
|
||||||
final static Logger logger = Logger.getLogger(AWSRDSService.class.getName());
|
final static Logger logger = Logger.getLogger(AWSRDSService.class.getName());
|
||||||
private AWSCredentialsProvider credentials;
|
private RdsClient rdsClient;
|
||||||
private AmazonRDS amazonRDS;
|
|
||||||
private String db_username;
|
private String db_username;
|
||||||
private String db_password;
|
private String db_password;
|
||||||
private String db_database;
|
private String db_database;
|
||||||
@ -34,22 +36,17 @@ public class AWSRDSService {
|
|||||||
* **/
|
* **/
|
||||||
public AWSRDSService() throws IOException {
|
public AWSRDSService() throws IOException {
|
||||||
//Init RDS client with credentials and region.
|
//Init RDS client with credentials and region.
|
||||||
credentials = new
|
|
||||||
AWSStaticCredentialsProvider(new
|
|
||||||
BasicAWSCredentials("<ACCESS_KEY>",
|
|
||||||
"<SECRET_KEY>"));
|
|
||||||
amazonRDS = AmazonRDSClientBuilder.standard().withCredentials(credentials)
|
|
||||||
.withRegion(Regions.AP_SOUTHEAST_2).build();
|
|
||||||
Properties prop = new Properties();
|
Properties prop = new Properties();
|
||||||
InputStream input = AWSRDSService.class.getClassLoader().getResourceAsStream("db.properties");
|
InputStream input = AWSRDSService.class.getClassLoader().getResourceAsStream("db.properties");
|
||||||
prop.load(input);
|
prop.load(input);
|
||||||
db_username = prop.getProperty("db_username");
|
db_username = prop.getProperty("db_username");
|
||||||
db_password = prop.getProperty("db_password");
|
db_password = prop.getProperty("db_password");
|
||||||
db_database = prop.getProperty("db_database");
|
db_database = prop.getProperty("db_database");
|
||||||
}
|
|
||||||
|
|
||||||
public AWSRDSService(AmazonRDS amazonRDS){
|
rdsClient = RdsClient.builder()
|
||||||
this.amazonRDS = amazonRDS;
|
.region(Region.AP_SOUTHEAST_2)
|
||||||
|
.credentialsProvider(ProfileCredentialsProvider.create("default"))
|
||||||
|
.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -60,29 +57,29 @@ public class AWSRDSService {
|
|||||||
public String launchInstance() {
|
public String launchInstance() {
|
||||||
|
|
||||||
String identifier = "";
|
String identifier = "";
|
||||||
CreateDBInstanceRequest request = new CreateDBInstanceRequest();
|
CreateDbInstanceRequest instanceRequest = CreateDbInstanceRequest.builder()
|
||||||
// RDS instance name
|
.dbInstanceIdentifier("Sydney")
|
||||||
request.setDBInstanceIdentifier("Sydney");
|
.engine("postgres")
|
||||||
request.setEngine("postgres");
|
.multiAZ(false)
|
||||||
request.setMultiAZ(false);
|
.masterUsername(db_username)
|
||||||
request.setMasterUsername(db_username);
|
.masterUserPassword(db_password)
|
||||||
request.setMasterUserPassword(db_password);
|
.dbName(db_database)
|
||||||
request.setDBName(db_database);
|
.storageType("gp2")
|
||||||
request.setStorageType("gp2");
|
.allocatedStorage(10)
|
||||||
request.setAllocatedStorage(10);
|
.build();
|
||||||
|
|
||||||
DBInstance instance = amazonRDS.createDBInstance(request);
|
CreateDbInstanceResponse createDbInstanceResponse = rdsClient.createDBInstance(instanceRequest);
|
||||||
|
|
||||||
// Information about the new RDS instance
|
// Information about the new RDS instance
|
||||||
identifier = instance.getDBInstanceIdentifier();
|
identifier = createDbInstanceResponse.dbInstance().dbInstanceIdentifier();
|
||||||
String status = instance.getDBInstanceStatus();
|
String status = createDbInstanceResponse.dbInstance().dbInstanceStatus();
|
||||||
Endpoint endpoint = instance.getEndpoint();
|
Endpoint endpoint = createDbInstanceResponse.dbInstance().endpoint();
|
||||||
String endpoint_url = "Endpoint URL not available yet.";
|
String endpointUrl = "Endpoint URL not available yet.";
|
||||||
if (endpoint != null) {
|
if (endpoint != null) {
|
||||||
endpoint_url = endpoint.toString();
|
endpointUrl = endpoint.toString();
|
||||||
}
|
}
|
||||||
logger.info(identifier + "\t" + status);
|
logger.info(identifier + "\t" + status);
|
||||||
logger.info(endpoint_url);
|
logger.info(endpointUrl);
|
||||||
|
|
||||||
return identifier;
|
return identifier;
|
||||||
|
|
||||||
@ -90,44 +87,44 @@ public class AWSRDSService {
|
|||||||
|
|
||||||
// Describe DB instances
|
// Describe DB instances
|
||||||
public void listInstances() {
|
public void listInstances() {
|
||||||
DescribeDBInstancesResult result = amazonRDS.describeDBInstances();
|
DescribeDbInstancesResponse response = rdsClient.describeDBInstances();
|
||||||
List<DBInstance> instances = result.getDBInstances();
|
List<DBInstance> instances = response.dbInstances();
|
||||||
for (DBInstance instance : instances) {
|
for (DBInstance instance : instances) {
|
||||||
// Information about each RDS instance
|
// Information about each RDS instance
|
||||||
String identifier = instance.getDBInstanceIdentifier();
|
String identifier = instance.dbInstanceIdentifier();
|
||||||
String engine = instance.getEngine();
|
String engine = instance.engine();
|
||||||
String status = instance.getDBInstanceStatus();
|
String status = instance.dbInstanceStatus();
|
||||||
Endpoint endpoint = instance.getEndpoint();
|
Endpoint endpoint = instance.endpoint();
|
||||||
String endpoint_url = "Endpoint URL not available yet.";
|
String endpointUrl = "Endpoint URL not available yet.";
|
||||||
if (endpoint != null) {
|
if (endpoint != null) {
|
||||||
endpoint_url = endpoint.toString();
|
endpointUrl = endpoint.toString();
|
||||||
}
|
}
|
||||||
logger.info(identifier + "\t" + engine + "\t" + status);
|
logger.info(identifier + "\t" + engine + "\t" + status);
|
||||||
logger.info("\t" + endpoint_url);
|
logger.info("\t" + endpointUrl);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
//Delete RDS instance
|
//Delete RDS instance
|
||||||
public void terminateInstance(String identifier) {
|
public void terminateInstance(String identifier) {
|
||||||
|
|
||||||
DeleteDBInstanceRequest request = new DeleteDBInstanceRequest();
|
DeleteDbInstanceRequest request = DeleteDbInstanceRequest.builder()
|
||||||
request.setDBInstanceIdentifier(identifier);
|
.dbInstanceIdentifier(identifier)
|
||||||
request.setSkipFinalSnapshot(true);
|
.skipFinalSnapshot(true)
|
||||||
|
.build();
|
||||||
|
|
||||||
// Delete the RDS instance
|
// Delete the RDS instance
|
||||||
DBInstance instance = amazonRDS.deleteDBInstance(request);
|
DeleteDbInstanceResponse response = rdsClient.deleteDBInstance(request);
|
||||||
|
|
||||||
// Information about the RDS instance being deleted
|
// Information about the RDS instance being deleted
|
||||||
String status = instance.getDBInstanceStatus();
|
String status = response.dbInstance().dbInstanceStatus();
|
||||||
Endpoint endpoint = instance.getEndpoint();
|
Endpoint endpoint = response.dbInstance().endpoint();
|
||||||
String endpoint_url = "Endpoint URL not available yet.";
|
String endpointUrl = "Endpoint URL not available yet.";
|
||||||
if (endpoint != null) {
|
if (endpoint != null) {
|
||||||
endpoint_url = endpoint.toString();
|
endpointUrl = endpoint.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.info(identifier + "\t" + status);
|
logger.info(identifier + "\t" + status);
|
||||||
logger.info(endpoint_url);
|
logger.info(endpointUrl);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -5,140 +5,190 @@ import java.util.HashMap;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
import com.amazonaws.auth.AWSCredentials;
|
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
|
||||||
import com.amazonaws.auth.AWSStaticCredentialsProvider;
|
import software.amazon.awssdk.regions.Region;
|
||||||
import com.amazonaws.auth.BasicAWSCredentials;
|
import software.amazon.awssdk.services.sqs.SqsClient;
|
||||||
import com.amazonaws.regions.Regions;
|
import software.amazon.awssdk.services.sqs.model.CreateQueueRequest;
|
||||||
import com.amazonaws.services.sqs.AmazonSQSClientBuilder;
|
import software.amazon.awssdk.services.sqs.model.DeleteMessageRequest;
|
||||||
import com.amazonaws.services.sqs.model.CreateQueueRequest;
|
import software.amazon.awssdk.services.sqs.model.GetQueueAttributesRequest;
|
||||||
import com.amazonaws.services.sqs.model.DeleteMessageRequest;
|
import software.amazon.awssdk.services.sqs.model.GetQueueAttributesResponse;
|
||||||
import com.amazonaws.services.sqs.model.GetQueueAttributesRequest;
|
import software.amazon.awssdk.services.sqs.model.GetQueueUrlRequest;
|
||||||
import com.amazonaws.services.sqs.model.GetQueueAttributesResult;
|
import software.amazon.awssdk.services.sqs.model.GetQueueUrlResponse;
|
||||||
import com.amazonaws.services.sqs.model.MessageAttributeValue;
|
import software.amazon.awssdk.services.sqs.model.Message;
|
||||||
import com.amazonaws.services.sqs.model.ReceiveMessageRequest;
|
import software.amazon.awssdk.services.sqs.model.MessageAttributeValue;
|
||||||
import com.amazonaws.services.sqs.model.SendMessageBatchRequest;
|
import software.amazon.awssdk.services.sqs.model.QueueAttributeName;
|
||||||
import com.amazonaws.services.sqs.model.SendMessageRequest;
|
import software.amazon.awssdk.services.sqs.model.ReceiveMessageRequest;
|
||||||
import com.amazonaws.services.sqs.model.SetQueueAttributesRequest;
|
import software.amazon.awssdk.services.sqs.model.SendMessageBatchRequest;
|
||||||
import com.amazonaws.services.sqs.model.SendMessageBatchRequestEntry;
|
import software.amazon.awssdk.services.sqs.model.SendMessageBatchRequestEntry;
|
||||||
import com.amazonaws.services.sqs.model.Message;
|
import software.amazon.awssdk.services.sqs.model.SendMessageRequest;
|
||||||
import com.amazonaws.services.sqs.AmazonSQS;
|
import software.amazon.awssdk.services.sqs.model.SetQueueAttributesRequest;
|
||||||
|
|
||||||
public class SQSApplication {
|
public class SQSApplication {
|
||||||
|
|
||||||
private static final AWSCredentials credentials;
|
private static final String STANDARD_QUEUE_NAME = "baeldung-queue";
|
||||||
|
private static final String FIFO_QUEUE_NAME = "baeldung-queue.fifo";
|
||||||
static {
|
private static final String DEAD_LETTER_QUEUE_NAME = "baeldung-dead-letter-queue";
|
||||||
// put your accesskey and secretkey here
|
|
||||||
credentials = new BasicAWSCredentials(
|
|
||||||
"<AWS accesskey>",
|
|
||||||
"<AWS secretkey>"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
|
|
||||||
// Set up the client
|
// Set up the client
|
||||||
AmazonSQS sqs = AmazonSQSClientBuilder.standard()
|
SqsClient sqsClient = SqsClient.builder()
|
||||||
.withCredentials(new AWSStaticCredentialsProvider(credentials))
|
.region(Region.US_EAST_1)
|
||||||
.withRegion(Regions.US_EAST_1)
|
.credentialsProvider(ProfileCredentialsProvider.create())
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
// Create a standard queue
|
// Create a standard queue
|
||||||
|
CreateQueueRequest createStandardQueueRequest = CreateQueueRequest.builder()
|
||||||
|
.queueName(STANDARD_QUEUE_NAME)
|
||||||
|
.build();
|
||||||
|
|
||||||
CreateQueueRequest createStandardQueueRequest = new CreateQueueRequest("baeldung-queue");
|
sqsClient.createQueue(createStandardQueueRequest);
|
||||||
String standardQueueUrl = sqs.createQueue(createStandardQueueRequest)
|
|
||||||
.getQueueUrl();
|
System.out.println("\nGet queue url");
|
||||||
|
|
||||||
|
GetQueueUrlResponse getQueueUrlResponse = sqsClient.getQueueUrl(GetQueueUrlRequest.builder()
|
||||||
|
.queueName(STANDARD_QUEUE_NAME)
|
||||||
|
.build());
|
||||||
|
String standardQueueUrl = getQueueUrlResponse.queueUrl();
|
||||||
|
|
||||||
System.out.println(standardQueueUrl);
|
System.out.println(standardQueueUrl);
|
||||||
|
|
||||||
// Create a fifo queue
|
// Create a fifo queue
|
||||||
|
Map<QueueAttributeName, String> queueAttributes = new HashMap<>();
|
||||||
|
queueAttributes.put(QueueAttributeName.FIFO_QUEUE, "true");
|
||||||
|
queueAttributes.put(QueueAttributeName.CONTENT_BASED_DEDUPLICATION, "true");
|
||||||
|
|
||||||
Map<String, String> queueAttributes = new HashMap<String, String>();
|
CreateQueueRequest createFifoQueueRequest = CreateQueueRequest.builder()
|
||||||
queueAttributes.put("FifoQueue", "true");
|
.queueName(FIFO_QUEUE_NAME)
|
||||||
queueAttributes.put("ContentBasedDeduplication", "true");
|
.attributes(queueAttributes)
|
||||||
|
.build();
|
||||||
|
|
||||||
CreateQueueRequest createFifoQueueRequest = new CreateQueueRequest("baeldung-queue.fifo").withAttributes(queueAttributes);
|
sqsClient.createQueue(createFifoQueueRequest);
|
||||||
String fifoQueueUrl = sqs.createQueue(createFifoQueueRequest)
|
|
||||||
.getQueueUrl();
|
GetQueueUrlResponse getFifoQueueUrlResponse = sqsClient.getQueueUrl(GetQueueUrlRequest.builder()
|
||||||
|
.queueName(FIFO_QUEUE_NAME)
|
||||||
|
.build());
|
||||||
|
|
||||||
|
String fifoQueueUrl = getFifoQueueUrlResponse.queueUrl();
|
||||||
|
|
||||||
System.out.println(fifoQueueUrl);
|
System.out.println(fifoQueueUrl);
|
||||||
|
|
||||||
// Set up a dead letter queue
|
// Set up a dead letter queue
|
||||||
|
CreateQueueRequest createDeadLetterQueueRequest = CreateQueueRequest.builder()
|
||||||
|
.queueName(DEAD_LETTER_QUEUE_NAME)
|
||||||
|
.build();
|
||||||
|
|
||||||
String deadLetterQueueUrl = sqs.createQueue("baeldung-dead-letter-queue")
|
String deadLetterQueueUrl = sqsClient.createQueue(createDeadLetterQueueRequest)
|
||||||
.getQueueUrl();
|
.queueUrl();
|
||||||
|
|
||||||
GetQueueAttributesResult deadLetterQueueAttributes = sqs.getQueueAttributes(new GetQueueAttributesRequest(deadLetterQueueUrl).withAttributeNames("QueueArn"));
|
GetQueueAttributesRequest getQueueAttributesRequest = GetQueueAttributesRequest.builder()
|
||||||
|
.queueUrl(deadLetterQueueUrl)
|
||||||
|
.attributeNames(QueueAttributeName.QUEUE_ARN)
|
||||||
|
.build();
|
||||||
|
|
||||||
String deadLetterQueueARN = deadLetterQueueAttributes.getAttributes()
|
GetQueueAttributesResponse deadLetterQueueAttributes = sqsClient.getQueueAttributes(getQueueAttributesRequest);
|
||||||
|
|
||||||
|
String deadLetterQueueARN = deadLetterQueueAttributes.attributes()
|
||||||
.get("QueueArn");
|
.get("QueueArn");
|
||||||
|
|
||||||
SetQueueAttributesRequest queueAttributesRequest = new SetQueueAttributesRequest().withQueueUrl(standardQueueUrl)
|
Map<QueueAttributeName, String> attributes = new HashMap<>();
|
||||||
.addAttributesEntry("RedrivePolicy", "{\"maxReceiveCount\":\"2\", " + "\"deadLetterTargetArn\":\"" + deadLetterQueueARN + "\"}");
|
attributes.put(QueueAttributeName.REDRIVE_POLICY, "{\"maxReceiveCount\":\"5\", \"deadLetterTargetArn\":\"" + deadLetterQueueARN + "\"}");
|
||||||
|
|
||||||
sqs.setQueueAttributes(queueAttributesRequest);
|
SetQueueAttributesRequest queueAttributesRequest = SetQueueAttributesRequest.builder()
|
||||||
|
.queueUrl(standardQueueUrl)
|
||||||
|
.attributes(attributes)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
sqsClient.setQueueAttributes(queueAttributesRequest);
|
||||||
|
|
||||||
// Send a message to a standard queue
|
// Send a message to a standard queue
|
||||||
|
|
||||||
Map<String, MessageAttributeValue> messageAttributes = new HashMap<>();
|
Map<String, MessageAttributeValue> messageAttributes = new HashMap<>();
|
||||||
|
MessageAttributeValue messageAttributeValue = MessageAttributeValue.builder()
|
||||||
|
.stringValue("This is an attribute")
|
||||||
|
.dataType("String")
|
||||||
|
.build();
|
||||||
|
|
||||||
messageAttributes.put("AttributeOne", new MessageAttributeValue().withStringValue("This is an attribute")
|
messageAttributes.put("AttributeOne", messageAttributeValue);
|
||||||
.withDataType("String"));
|
|
||||||
|
|
||||||
SendMessageRequest sendMessageStandardQueue = new SendMessageRequest().withQueueUrl(standardQueueUrl)
|
SendMessageRequest sendMessageStandardQueue = SendMessageRequest.builder()
|
||||||
.withMessageBody("A simple message.")
|
.queueUrl(standardQueueUrl)
|
||||||
.withDelaySeconds(30) // Message will arrive in the queue after 30 seconds. We can use this only in standard queues
|
.messageBody("A simple message.")
|
||||||
.withMessageAttributes(messageAttributes);
|
.delaySeconds(30) // Message will arrive in the queue after 30 seconds. We can use this only in standard queues
|
||||||
|
.messageAttributes(messageAttributes)
|
||||||
|
.build();
|
||||||
|
|
||||||
sqs.sendMessage(sendMessageStandardQueue);
|
sqsClient.sendMessage(sendMessageStandardQueue);
|
||||||
|
|
||||||
// Send a message to a fifo queue
|
// Send a message to a fifo queue
|
||||||
|
|
||||||
SendMessageRequest sendMessageFifoQueue = new SendMessageRequest().withQueueUrl(fifoQueueUrl)
|
SendMessageRequest sendMessageFifoQueue = SendMessageRequest.builder()
|
||||||
.withMessageBody("FIFO Queue")
|
.queueUrl(fifoQueueUrl)
|
||||||
.withMessageGroupId("baeldung-group-1")
|
.messageBody("FIFO Queue")
|
||||||
.withMessageAttributes(messageAttributes);
|
.messageGroupId("baeldung-group-1")
|
||||||
|
.messageAttributes(messageAttributes)
|
||||||
|
.build();
|
||||||
|
|
||||||
sqs.sendMessage(sendMessageFifoQueue);
|
sqsClient.sendMessage(sendMessageFifoQueue);
|
||||||
|
|
||||||
// Send multiple messages
|
// Send multiple messages
|
||||||
|
|
||||||
List<SendMessageBatchRequestEntry> messageEntries = new ArrayList<>();
|
List<SendMessageBatchRequestEntry> messageEntries = new ArrayList<>();
|
||||||
messageEntries.add(new SendMessageBatchRequestEntry().withId("id-1")
|
SendMessageBatchRequestEntry messageBatchRequestEntry1 = SendMessageBatchRequestEntry.builder()
|
||||||
.withMessageBody("batch-1")
|
.id("id-1")
|
||||||
.withMessageGroupId("baeldung-group-1"));
|
.messageBody("batch-1")
|
||||||
messageEntries.add(new SendMessageBatchRequestEntry().withId("id-2")
|
.messageGroupId("baeldung-group-1")
|
||||||
.withMessageBody("batch-2")
|
.build();
|
||||||
.withMessageGroupId("baeldung-group-1"));
|
|
||||||
|
|
||||||
SendMessageBatchRequest sendMessageBatchRequest = new SendMessageBatchRequest(fifoQueueUrl, messageEntries);
|
SendMessageBatchRequestEntry messageBatchRequestEntry2 = SendMessageBatchRequestEntry.builder()
|
||||||
sqs.sendMessageBatch(sendMessageBatchRequest);
|
.id("id-2")
|
||||||
|
.messageBody("batch-2")
|
||||||
|
.messageGroupId("baeldung-group-1")
|
||||||
|
.build();
|
||||||
|
|
||||||
|
messageEntries.add(messageBatchRequestEntry1);
|
||||||
|
messageEntries.add(messageBatchRequestEntry2);
|
||||||
|
|
||||||
|
SendMessageBatchRequest sendMessageBatchRequest = SendMessageBatchRequest.builder()
|
||||||
|
.queueUrl(fifoQueueUrl)
|
||||||
|
.entries(messageEntries)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
sqsClient.sendMessageBatch(sendMessageBatchRequest);
|
||||||
|
|
||||||
// Read a message from a queue
|
// Read a message from a queue
|
||||||
|
|
||||||
ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(fifoQueueUrl).withWaitTimeSeconds(10) // Long polling;
|
ReceiveMessageRequest receiveMessageRequest = ReceiveMessageRequest.builder()
|
||||||
.withMaxNumberOfMessages(1); // Max is 10
|
.waitTimeSeconds(10)
|
||||||
|
.maxNumberOfMessages(10)
|
||||||
|
.build();
|
||||||
|
|
||||||
List<Message> sqsMessages = sqs.receiveMessage(receiveMessageRequest)
|
List<Message> sqsMessages = sqsClient.receiveMessage(receiveMessageRequest)
|
||||||
.getMessages();
|
.messages();
|
||||||
|
|
||||||
sqsMessages.get(0)
|
sqsMessages.get(0)
|
||||||
.getAttributes();
|
.attributes();
|
||||||
sqsMessages.get(0)
|
sqsMessages.get(0)
|
||||||
.getBody();
|
.body();
|
||||||
|
|
||||||
// Delete a message from a queue
|
// Delete a message from a queue
|
||||||
|
DeleteMessageRequest deleteMessageRequest = DeleteMessageRequest.builder()
|
||||||
|
.queueUrl(fifoQueueUrl)
|
||||||
|
.receiptHandle(sqsMessages.get(0)
|
||||||
|
.receiptHandle())
|
||||||
|
.build();
|
||||||
|
|
||||||
sqs.deleteMessage(new DeleteMessageRequest().withQueueUrl(fifoQueueUrl)
|
sqsClient.deleteMessage(deleteMessageRequest);
|
||||||
.withReceiptHandle(sqsMessages.get(0)
|
|
||||||
.getReceiptHandle()));
|
|
||||||
|
|
||||||
// Monitoring
|
// Monitoring
|
||||||
GetQueueAttributesRequest getQueueAttributesRequest = new GetQueueAttributesRequest(standardQueueUrl).withAttributeNames("All");
|
GetQueueAttributesRequest getQueueAttributesRequestForMonitoring = GetQueueAttributesRequest.builder()
|
||||||
GetQueueAttributesResult getQueueAttributesResult = sqs.getQueueAttributes(getQueueAttributesRequest);
|
.queueUrl(standardQueueUrl)
|
||||||
System.out.println(String.format("The number of messages on the queue: %s", getQueueAttributesResult.getAttributes()
|
.build();
|
||||||
|
|
||||||
|
GetQueueAttributesResponse attributesResponse = sqsClient.getQueueAttributes(getQueueAttributesRequestForMonitoring);
|
||||||
|
System.out.println(String.format("The number of messages on the queue: %s", attributesResponse.attributes()
|
||||||
.get("ApproximateNumberOfMessages")));
|
.get("ApproximateNumberOfMessages")));
|
||||||
System.out.println(String.format("The number of messages in flight: %s", getQueueAttributesResult.getAttributes()
|
System.out.println(String.format("The number of messages in flight: %s", attributesResponse.attributes()
|
||||||
.get("ApproximateNumberOfMessagesNotVisible")));
|
.get("ApproximateNumberOfMessagesNotVisible")));
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -5,6 +5,14 @@
|
|||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<artifactId>aws-modules</artifactId>
|
<artifactId>aws-modules</artifactId>
|
||||||
<name>aws-modules</name>
|
<name>aws-modules</name>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.amazonaws</groupId>
|
||||||
|
<artifactId>aws-java-sdk-dynamodb</artifactId>
|
||||||
|
<version>1.12.523</version>
|
||||||
|
<scope>compile</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
<packaging>pom</packaging>
|
<packaging>pom</packaging>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
@ -15,6 +23,7 @@
|
|||||||
|
|
||||||
<modules>
|
<modules>
|
||||||
<module>aws-app-sync</module>
|
<module>aws-app-sync</module>
|
||||||
|
<module>aws-dynamodb</module>
|
||||||
<module>aws-lambda-modules</module>
|
<module>aws-lambda-modules</module>
|
||||||
<module>aws-miscellaneous</module>
|
<module>aws-miscellaneous</module>
|
||||||
<module>aws-reactive</module>
|
<module>aws-reactive</module>
|
||||||
@ -24,6 +33,7 @@
|
|||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<aws-java-sdk.version>1.12.331</aws-java-sdk.version>
|
<aws-java-sdk.version>1.12.331</aws-java-sdk.version>
|
||||||
|
<aws-java-sdk-v2.version>2.20.147</aws-java-sdk-v2.version>
|
||||||
<maven-shade-plugin.version>3.0.0</maven-shade-plugin.version>
|
<maven-shade-plugin.version>3.0.0</maven-shade-plugin.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
|
@ -5,7 +5,6 @@ This module contains articles about Java 11 core features
|
|||||||
### Relevant articles
|
### Relevant articles
|
||||||
- [Guide To Java 8 Optional](https://www.baeldung.com/java-optional)
|
- [Guide To Java 8 Optional](https://www.baeldung.com/java-optional)
|
||||||
- [Guide to Java Reflection](http://www.baeldung.com/java-reflection)
|
- [Guide to Java Reflection](http://www.baeldung.com/java-reflection)
|
||||||
- [Guide to Java 8’s Collectors](https://www.baeldung.com/java-8-collectors)
|
|
||||||
- [New Features in Java 11](https://www.baeldung.com/java-11-new-features)
|
- [New Features in Java 11](https://www.baeldung.com/java-11-new-features)
|
||||||
- [Getting the Java Version at Runtime](https://www.baeldung.com/get-java-version-runtime)
|
- [Getting the Java Version at Runtime](https://www.baeldung.com/get-java-version-runtime)
|
||||||
- [Invoking a SOAP Web Service in Java](https://www.baeldung.com/java-soap-web-service)
|
- [Invoking a SOAP Web Service in Java](https://www.baeldung.com/java-soap-web-service)
|
||||||
|
@ -4,5 +4,4 @@
|
|||||||
- [Guide to mapMulti in Stream API](https://www.baeldung.com/java-mapmulti)
|
- [Guide to mapMulti in Stream API](https://www.baeldung.com/java-mapmulti)
|
||||||
- [Collecting Stream Elements into a List in Java](https://www.baeldung.com/java-stream-to-list-collecting)
|
- [Collecting Stream Elements into a List in Java](https://www.baeldung.com/java-stream-to-list-collecting)
|
||||||
- [New Features in Java 16](https://www.baeldung.com/java-16-new-features)
|
- [New Features in Java 16](https://www.baeldung.com/java-16-new-features)
|
||||||
- [Guide to Java 8 groupingBy Collector](https://www.baeldung.com/java-groupingby-collector)
|
|
||||||
- [Value-Based Classes in Java](https://www.baeldung.com/java-value-based-classes)
|
- [Value-Based Classes in Java](https://www.baeldung.com/java-value-based-classes)
|
||||||
|
@ -30,6 +30,11 @@ public final class Point {
|
|||||||
return new Point(x, y, z);
|
return new Point(x, y, z);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "Point{" + "x=" + x + ", y=" + y + ", z=" + z + '}';
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean equals(Object other) {
|
public boolean equals(Object other) {
|
||||||
if (other == null || getClass() != other.getClass())
|
if (other == null || getClass() != other.getClass())
|
||||||
|
@ -1,14 +1,17 @@
|
|||||||
package com.baeldung.value_based_class;
|
package com.baeldung.value_based_class;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class ValueBasedClassUnitTest {
|
public class ValueBasedClassUnitTest {
|
||||||
@Test
|
@Test
|
||||||
public void givenAutoboxedAndPrimitive_whenCompared_thenReturnEquals() {
|
public void givenAutoboxedAndPrimitive_whenCompared_thenReturnEquals() {
|
||||||
int primitive_a = 125;
|
List<Integer> list = new ArrayList<>();
|
||||||
Integer obj_a = 125; // this is autoboxed
|
list.add(1); // this is autoboxed
|
||||||
Assert.assertSame(primitive_a, obj_a);
|
Assert.assertEquals(list.get(0), Integer.valueOf(1));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
89
core-java-modules/core-java-17/src/test/java/com/baeldung/recordproperties/ReadRecordPropertiesByReflectionUnitTest.java
Normal file
89
core-java-modules/core-java-17/src/test/java/com/baeldung/recordproperties/ReadRecordPropertiesByReflectionUnitTest.java
Normal file
@ -0,0 +1,89 @@
|
|||||||
|
package com.baeldung.recordproperties;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
import java.lang.reflect.Field;
|
||||||
|
import java.lang.reflect.RecordComponent;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
record Player(String name, int age, Long score) {
|
||||||
|
}
|
||||||
|
|
||||||
|
public class ReadRecordPropertiesByReflectionUnitTest {
|
||||||
|
private static final Player ERIC = new Player("Eric", 28, 4242L);
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingRecordComponent_thenGetExpectedResult() {
|
||||||
|
var fields = new ArrayList<Field>();
|
||||||
|
RecordComponent[] components = Player.class.getRecordComponents();
|
||||||
|
for (var comp : components) {
|
||||||
|
try {
|
||||||
|
Field field = ERIC.getClass()
|
||||||
|
.getDeclaredField(comp.getName());
|
||||||
|
field.setAccessible(true);
|
||||||
|
fields.add(field);
|
||||||
|
} catch (NoSuchFieldException e) {
|
||||||
|
// for simplicity, error handling is skipped
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals(3, fields.size());
|
||||||
|
|
||||||
|
var nameField = fields.get(0);
|
||||||
|
var ageField = fields.get(1);
|
||||||
|
var scoreField = fields.get(2);
|
||||||
|
try {
|
||||||
|
assertEquals("name", nameField.getName());
|
||||||
|
assertEquals(String.class, nameField.getType());
|
||||||
|
assertEquals("Eric", nameField.get(ERIC));
|
||||||
|
|
||||||
|
assertEquals("age", ageField.getName());
|
||||||
|
assertEquals(int.class, ageField.getType());
|
||||||
|
assertEquals(28, ageField.get(ERIC));
|
||||||
|
|
||||||
|
assertEquals("score", scoreField.getName());
|
||||||
|
assertEquals(Long.class, scoreField.getType());
|
||||||
|
assertEquals(4242L, scoreField.get(ERIC));
|
||||||
|
} catch (IllegalAccessException exception) {
|
||||||
|
// for simplicity, error handling is skipped
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingClassGetDeclaredField_thenGetExpectedResult() {
|
||||||
|
// record has no public fields
|
||||||
|
assertEquals(0, Player.class.getFields().length);
|
||||||
|
|
||||||
|
var fields = new ArrayList<Field>();
|
||||||
|
for (var field : Player.class.getDeclaredFields()) {
|
||||||
|
field.setAccessible(true);
|
||||||
|
fields.add(field);
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals(3, fields.size());
|
||||||
|
var nameField = fields.get(0);
|
||||||
|
var ageField = fields.get(1);
|
||||||
|
var scoreField = fields.get(2);
|
||||||
|
|
||||||
|
try {
|
||||||
|
assertEquals("name", nameField.getName());
|
||||||
|
assertEquals(String.class, nameField.getType());
|
||||||
|
assertEquals("Eric", nameField.get(ERIC));
|
||||||
|
|
||||||
|
assertEquals("age", ageField.getName());
|
||||||
|
assertEquals(int.class, ageField.getType());
|
||||||
|
assertEquals(28, ageField.get(ERIC));
|
||||||
|
|
||||||
|
assertEquals("score", scoreField.getName());
|
||||||
|
assertEquals(Long.class, scoreField.getType());
|
||||||
|
assertEquals(4242L, scoreField.get(ERIC));
|
||||||
|
} catch (IllegalAccessException ex) {
|
||||||
|
// for simplicity, error handling is skipped
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
0
core-java-modules/core-java-18/README.md
Normal file
0
core-java-modules/core-java-18/README.md
Normal file
55
core-java-modules/core-java-18/pom.xml
Normal file
55
core-java-modules/core-java-18/pom.xml
Normal file
@ -0,0 +1,55 @@
|
|||||||
|
<?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-18</artifactId>
|
||||||
|
<name>core-java-18</name>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>parent-modules</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
<relativePath>../../</relativePath>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>${maven-compiler-plugin.version}</version>
|
||||||
|
<configuration>
|
||||||
|
<release>${maven.compiler.release}</release>
|
||||||
|
<compilerArgs>--enable-preview</compilerArgs>
|
||||||
|
<source>${maven.compiler.source.version}</source>
|
||||||
|
<target>${maven.compiler.target.version}</target>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
|
<version>${surefire.plugin.version}</version>
|
||||||
|
<configuration>
|
||||||
|
<forkCount>1</forkCount>
|
||||||
|
</configuration>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.maven.surefire</groupId>
|
||||||
|
<artifactId>surefire-api</artifactId>
|
||||||
|
<version>${surefire.plugin.version}</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<maven.compiler.source.version>18</maven.compiler.source.version>
|
||||||
|
<maven.compiler.target.version>18</maven.compiler.target.version>
|
||||||
|
<maven.compiler.release>18</maven.compiler.release>
|
||||||
|
<surefire.plugin.version>3.0.0-M5</surefire.plugin.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
</project>
|
27
core-java-modules/core-java-18/src/main/java/com/baeldung/finalization_closeable_cleaner/FinalizationExamples.java
Normal file
27
core-java-modules/core-java-18/src/main/java/com/baeldung/finalization_closeable_cleaner/FinalizationExamples.java
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
package com.baeldung.finalization_closeable_cleaner;
|
||||||
|
|
||||||
|
import java.io.FileInputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
public class FinalizationExamples {
|
||||||
|
FileInputStream fis = null;
|
||||||
|
|
||||||
|
public void readFileOperationWithFinalization() throws IOException {
|
||||||
|
try {
|
||||||
|
fis = new FileInputStream("input.txt");
|
||||||
|
// perform operation on the file
|
||||||
|
System.out.println(fis.readAllBytes().length);
|
||||||
|
|
||||||
|
} finally {
|
||||||
|
if (fis != null)
|
||||||
|
fis.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void readFileOperationWithTryWith() throws IOException {
|
||||||
|
try (FileInputStream fis = new FileInputStream("input.txt")) {
|
||||||
|
// perform operations
|
||||||
|
System.out.println(fis.readAllBytes().length);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
48
core-java-modules/core-java-18/src/main/java/com/baeldung/finalization_closeable_cleaner/MyCleanerResourceClass.java
Normal file
48
core-java-modules/core-java-18/src/main/java/com/baeldung/finalization_closeable_cleaner/MyCleanerResourceClass.java
Normal file
@ -0,0 +1,48 @@
|
|||||||
|
package com.baeldung.finalization_closeable_cleaner;
|
||||||
|
|
||||||
|
import java.lang.ref.Cleaner;
|
||||||
|
|
||||||
|
public class MyCleanerResourceClass implements AutoCloseable {
|
||||||
|
private static Resource resource;
|
||||||
|
|
||||||
|
private static final Cleaner cleaner = Cleaner.create();
|
||||||
|
private final Cleaner.Cleanable cleanable;
|
||||||
|
|
||||||
|
public MyCleanerResourceClass() {
|
||||||
|
resource = new Resource();
|
||||||
|
this.cleanable = cleaner.register(this, new CleaningState());
|
||||||
|
}
|
||||||
|
|
||||||
|
public void useResource() {
|
||||||
|
// using the resource here
|
||||||
|
resource.use();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void close() {
|
||||||
|
// perform actions to close all underlying resources
|
||||||
|
this.cleanable.clean();
|
||||||
|
}
|
||||||
|
|
||||||
|
static class CleaningState implements Runnable {
|
||||||
|
CleaningState() {
|
||||||
|
// constructor
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
// some cleanup action
|
||||||
|
System.out.println("Cleanup done");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static class Resource {
|
||||||
|
void use() {
|
||||||
|
System.out.println("Using the resource");
|
||||||
|
}
|
||||||
|
|
||||||
|
void close() {
|
||||||
|
System.out.println("Cleanup done");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
25
core-java-modules/core-java-18/src/main/java/com/baeldung/finalization_closeable_cleaner/MyCloseableResourceClass.java
Normal file
25
core-java-modules/core-java-18/src/main/java/com/baeldung/finalization_closeable_cleaner/MyCloseableResourceClass.java
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
package com.baeldung.finalization_closeable_cleaner;
|
||||||
|
|
||||||
|
import java.io.FileInputStream;
|
||||||
|
import java.io.FileNotFoundException;
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
public class MyCloseableResourceClass implements AutoCloseable {
|
||||||
|
|
||||||
|
private final FileInputStream fis;
|
||||||
|
|
||||||
|
public MyCloseableResourceClass() throws FileNotFoundException {
|
||||||
|
this.fis = new FileInputStream("src/main/resources/file.txt");
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getByteLength() throws IOException {
|
||||||
|
System.out.println("Some operation");
|
||||||
|
return this.fis.readAllBytes().length;
|
||||||
|
}
|
||||||
|
@Override
|
||||||
|
public void close() throws IOException {
|
||||||
|
System.out.println("Finalized object");
|
||||||
|
this.fis.close();
|
||||||
|
}
|
||||||
|
}
|
24
core-java-modules/core-java-18/src/main/java/com/baeldung/finalization_closeable_cleaner/MyFinalizableResourceClass.java
Normal file
24
core-java-modules/core-java-18/src/main/java/com/baeldung/finalization_closeable_cleaner/MyFinalizableResourceClass.java
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
package com.baeldung.finalization_closeable_cleaner;
|
||||||
|
|
||||||
|
import java.io.FileInputStream;
|
||||||
|
import java.io.FileNotFoundException;
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
public class MyFinalizableResourceClass {
|
||||||
|
private FileInputStream fis;
|
||||||
|
|
||||||
|
public MyFinalizableResourceClass() throws FileNotFoundException {
|
||||||
|
this.fis = new FileInputStream("src/main/resources/file.txt");
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getByteLength() throws IOException {
|
||||||
|
System.out.println("Some operation");
|
||||||
|
return this.fis.readAllBytes().length;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void finalize() throws Throwable {
|
||||||
|
System.out.println("Finalized object");
|
||||||
|
this.fis.close();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1 @@
|
|||||||
|
This is a test file.
|
36
core-java-modules/core-java-18/src/test/java/com/baeldung/finalization_closeable_cleaner/FinalizationCloseableCleanerUnitTest.java
Normal file
36
core-java-modules/core-java-18/src/test/java/com/baeldung/finalization_closeable_cleaner/FinalizationCloseableCleanerUnitTest.java
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
package com.baeldung.finalization_closeable_cleaner;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class FinalizationCloseableCleanerUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMyFinalizationResource_whenUsingFinalize_thenShouldClean() {
|
||||||
|
assertDoesNotThrow(() -> {
|
||||||
|
MyFinalizableResourceClass mfr = new MyFinalizableResourceClass();
|
||||||
|
mfr.getByteLength();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
@Test
|
||||||
|
public void givenMyCleanerResource_whenUsingCleanerAPI_thenShouldClean() {
|
||||||
|
assertDoesNotThrow(() -> {
|
||||||
|
try (MyCleanerResourceClass myCleanerResourceClass = new MyCleanerResourceClass()) {
|
||||||
|
myCleanerResourceClass.useResource();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCloseableResource_whenUsingTryWith_thenShouldClose() throws IOException {
|
||||||
|
int length = 0;
|
||||||
|
try (MyCloseableResourceClass mcr = new MyCloseableResourceClass()) {
|
||||||
|
length = mcr.getByteLength();
|
||||||
|
}
|
||||||
|
Assert.assertEquals(20, length);
|
||||||
|
}
|
||||||
|
}
|
@ -10,3 +10,4 @@ This module contains articles about arrays conversion in Java
|
|||||||
- [Convert Java Array to Iterable](https://www.baeldung.com/java-array-convert-to-iterable)
|
- [Convert Java Array to Iterable](https://www.baeldung.com/java-array-convert-to-iterable)
|
||||||
- [Converting an int[] to HashSet in Java](https://www.baeldung.com/java-converting-int-array-to-hashset)
|
- [Converting an int[] to HashSet in Java](https://www.baeldung.com/java-converting-int-array-to-hashset)
|
||||||
- [Convert an ArrayList of String to a String Array in Java](https://www.baeldung.com/java-convert-string-arraylist-array)
|
- [Convert an ArrayList of String to a String Array in Java](https://www.baeldung.com/java-convert-string-arraylist-array)
|
||||||
|
- [Convert Char Array to Int Array in Java](https://www.baeldung.com/java-convert-char-int-array)
|
||||||
|
67
core-java-modules/core-java-arrays-convert/src/main/java/com/baeldung/array/conversions/CharArrayToIntArrayUtils.java
Normal file
67
core-java-modules/core-java-arrays-convert/src/main/java/com/baeldung/array/conversions/CharArrayToIntArrayUtils.java
Normal file
@ -0,0 +1,67 @@
|
|||||||
|
package com.baeldung.array.conversions;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
public class CharArrayToIntArrayUtils {
|
||||||
|
|
||||||
|
static int[] usingGetNumericValueMethod(char[] chars) {
|
||||||
|
if (chars == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
int[] ints = new int[chars.length];
|
||||||
|
for (int i = 0; i < chars.length; i++) {
|
||||||
|
ints[i] = Character.getNumericValue(chars[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return ints;
|
||||||
|
}
|
||||||
|
|
||||||
|
static int[] usingDigitMethod(char[] chars) {
|
||||||
|
if (chars == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
int[] ints = new int[chars.length];
|
||||||
|
for (int i = 0; i < chars.length; i++) {
|
||||||
|
ints[i] = Character.digit(chars[i], 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
return ints;
|
||||||
|
}
|
||||||
|
|
||||||
|
static int[] usingStreamApiMethod(char[] chars) {
|
||||||
|
if (chars == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return new String(chars).chars()
|
||||||
|
.map(c -> c - 48)
|
||||||
|
.toArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
static int[] usingParseIntMethod(char[] chars) {
|
||||||
|
if (chars == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
int[] ints = new int[chars.length];
|
||||||
|
for (int i = 0; i < chars.length; i++) {
|
||||||
|
ints[i] = Integer.parseInt(String.valueOf(chars[i]));
|
||||||
|
}
|
||||||
|
|
||||||
|
return ints;
|
||||||
|
}
|
||||||
|
|
||||||
|
static int[] usingArraysSetAllMethod(char[] chars) {
|
||||||
|
if (chars == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
int[] ints = new int[chars.length];
|
||||||
|
Arrays.setAll(ints, i -> Character.getNumericValue(chars[i]));
|
||||||
|
|
||||||
|
return ints;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
54
core-java-modules/core-java-arrays-convert/src/test/java/com/baeldung/array/conversions/CharArrayToIntArrayUtilsUnitTest.java
Normal file
54
core-java-modules/core-java-arrays-convert/src/test/java/com/baeldung/array/conversions/CharArrayToIntArrayUtilsUnitTest.java
Normal file
@ -0,0 +1,54 @@
|
|||||||
|
package com.baeldung.array.conversions;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
class CharArrayToIntArrayUtilsUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenCharArray_whenUsingGetNumericValueMethod_shouldGetIntArray() {
|
||||||
|
int[] expected = { 2, 3, 4, 5 };
|
||||||
|
char[] chars = { '2', '3', '4', '5' };
|
||||||
|
int[] result = CharArrayToIntArrayUtils.usingGetNumericValueMethod(chars);
|
||||||
|
|
||||||
|
assertArrayEquals(expected, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenCharArray_whenUsingDigitMethod_shouldGetIntArray() {
|
||||||
|
int[] expected = { 1, 2, 3, 6 };
|
||||||
|
char[] chars = { '1', '2', '3', '6' };
|
||||||
|
int[] result = CharArrayToIntArrayUtils.usingDigitMethod(chars);
|
||||||
|
|
||||||
|
assertArrayEquals(expected, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenCharArray_whenUsingStreamApi_shouldGetIntArray() {
|
||||||
|
int[] expected = { 9, 8, 7, 6 };
|
||||||
|
char[] chars = { '9', '8', '7', '6' };
|
||||||
|
int[] result = CharArrayToIntArrayUtils.usingStreamApiMethod(chars);
|
||||||
|
|
||||||
|
assertArrayEquals(expected, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenCharArray_whenUsingParseIntMethod_shouldGetIntArray() {
|
||||||
|
int[] expected = { 9, 8, 7, 6 };
|
||||||
|
char[] chars = { '9', '8', '7', '6' };
|
||||||
|
int[] result = CharArrayToIntArrayUtils.usingParseIntMethod(chars);
|
||||||
|
|
||||||
|
assertArrayEquals(expected, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenCharArray_whenUsingArraysSetAllMethod_shouldGetIntArray() {
|
||||||
|
int[] expected = { 4, 9, 2, 3 };
|
||||||
|
char[] chars = { '4', '9', '2', '3' };
|
||||||
|
int[] result = CharArrayToIntArrayUtils.usingArraysSetAllMethod(chars);
|
||||||
|
|
||||||
|
assertArrayEquals(expected, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -123,6 +123,7 @@ public class HttpClientPost {
|
|||||||
|
|
||||||
HttpRequest request = HttpRequest.newBuilder()
|
HttpRequest request = HttpRequest.newBuilder()
|
||||||
.uri(URI.create(serviceUrl))
|
.uri(URI.create(serviceUrl))
|
||||||
|
.header("Content-Type", "application/x-www-form-urlencoded")
|
||||||
.POST(HttpRequest.BodyPublishers.ofString(getFormDataAsString(formData)))
|
.POST(HttpRequest.BodyPublishers.ofString(getFormDataAsString(formData)))
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
|
72
core-java-modules/core-java-io-5/src/test/java/com/baeldung/rmlinebreaks/RemoveLinebreaksUnitTest.java
Normal file
72
core-java-modules/core-java-io-5/src/test/java/com/baeldung/rmlinebreaks/RemoveLinebreaksUnitTest.java
Normal file
@ -0,0 +1,72 @@
|
|||||||
|
package com.baeldung.rmlinebreaks;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||||
|
|
||||||
|
public class RemoveLinebreaksUnitTest {
|
||||||
|
|
||||||
|
private Path file1Path() throws Exception {
|
||||||
|
return Paths.get(this.getClass().getClassLoader().getResource("multiple-line-1.txt").toURI());
|
||||||
|
}
|
||||||
|
|
||||||
|
private Path file2Path() throws Exception {
|
||||||
|
return Paths.get(this.getClass().getClassLoader().getResource("multiple-line-2.txt").toURI());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenRemovingLineSeparatorFromFile1_thenGetTheExpectedResult() throws Exception {
|
||||||
|
String content = Files.readString(file1Path(), StandardCharsets.UTF_8);
|
||||||
|
|
||||||
|
String result = content.replace(System.getProperty("line.separator"), "");
|
||||||
|
assertEquals("A, B, C, D, E, F", result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenRemovingLineSeparatorFromFile2_thenNotGetTheExpectedResult() throws Exception {
|
||||||
|
String content = Files.readString(file2Path(), StandardCharsets.UTF_8);
|
||||||
|
|
||||||
|
String result = content.replace(System.getProperty("line.separator"), "");
|
||||||
|
assertNotEquals("A, B, C, D, E, F", result); // <-- NOT equals assertion!
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenRemovingAllLinebreaks_thenGetTheExpectedResult() throws Exception {
|
||||||
|
String content1 = Files.readString(file1Path(), StandardCharsets.UTF_8);
|
||||||
|
|
||||||
|
// file contains CRLF
|
||||||
|
String content2 = Files.readString(file2Path(), StandardCharsets.UTF_8);
|
||||||
|
|
||||||
|
String result1 = content1.replace("\r", "").replace("\n", "");
|
||||||
|
String result2 = content2.replace("\r", "").replace("\n", "");
|
||||||
|
|
||||||
|
assertEquals("A, B, C, D, E, F", result1);
|
||||||
|
assertEquals("A, B, C, D, E, F", result2);
|
||||||
|
|
||||||
|
String resultReplaceAll = content2.replaceAll("[\\n\\r]", "");
|
||||||
|
assertEquals("A, B, C, D, E, F", resultReplaceAll);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingReadAllLinesAndJoin_thenGetExpectedResult() throws Exception {
|
||||||
|
List<String> lines1 = Files.readAllLines(file1Path(), StandardCharsets.UTF_8);
|
||||||
|
|
||||||
|
// file contains CRLF
|
||||||
|
List<String> lines2 = Files.readAllLines(file2Path(), StandardCharsets.UTF_8);
|
||||||
|
|
||||||
|
String result1 = String.join("", lines1);
|
||||||
|
String result2 = String.join("", lines2);
|
||||||
|
|
||||||
|
assertEquals("A, B, C, D, E, F", result1);
|
||||||
|
assertEquals("A, B, C, D, E, F", result2);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,6 @@
|
|||||||
|
A,
|
||||||
|
B,
|
||||||
|
C,
|
||||||
|
D,
|
||||||
|
E,
|
||||||
|
F
|
@ -0,0 +1,4 @@
|
|||||||
|
A,
B,
|
||||||
|
C,
|
||||||
|
D,
E,
|
||||||
|
F
|
7
core-java-modules/core-java-lang-oop-others/src/main/java/com/baeldung/encapsulation/Book.java
Normal file
7
core-java-modules/core-java-lang-oop-others/src/main/java/com/baeldung/encapsulation/Book.java
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
package com.baeldung.encapsulation;
|
||||||
|
|
||||||
|
public class Book {
|
||||||
|
public String author;
|
||||||
|
public int isbn;
|
||||||
|
|
||||||
|
}
|
8
core-java-modules/core-java-lang-oop-others/src/main/java/com/baeldung/encapsulation/BookDetails.java
Normal file
8
core-java-modules/core-java-lang-oop-others/src/main/java/com/baeldung/encapsulation/BookDetails.java
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
package com.baeldung.encapsulation;
|
||||||
|
|
||||||
|
public class BookDetails {
|
||||||
|
|
||||||
|
public String bookDetails(Book book) {
|
||||||
|
return "author name: " + book.author + " ISBN: " + book.isbn;
|
||||||
|
}
|
||||||
|
}
|
17
core-java-modules/core-java-lang-oop-others/src/main/java/com/baeldung/encapsulation/BookEncapsulation.java
Normal file
17
core-java-modules/core-java-lang-oop-others/src/main/java/com/baeldung/encapsulation/BookEncapsulation.java
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
package com.baeldung.encapsulation;
|
||||||
|
|
||||||
|
public class BookEncapsulation {
|
||||||
|
public String author;
|
||||||
|
public int isbn;
|
||||||
|
public int id = 1;
|
||||||
|
|
||||||
|
public BookEncapsulation(String author, int isbn) {
|
||||||
|
this.author = author;
|
||||||
|
this.isbn = isbn;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getBookDetails() {
|
||||||
|
return "author id: " + id + " author name: " + author + " ISBN: " + isbn;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
36
core-java-modules/core-java-lang-oop-others/src/main/java/com/baeldung/encapsulation/BookInformationHiding.java
Normal file
36
core-java-modules/core-java-lang-oop-others/src/main/java/com/baeldung/encapsulation/BookInformationHiding.java
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
package com.baeldung.encapsulation;
|
||||||
|
|
||||||
|
public class BookInformationHiding {
|
||||||
|
private String author;
|
||||||
|
private int isbn;
|
||||||
|
private int id = 1;
|
||||||
|
|
||||||
|
public BookInformationHiding(String author, int isbn) {
|
||||||
|
setAuthor(author);
|
||||||
|
setIsbn(isbn);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getAuthor() {
|
||||||
|
return author;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setAuthor(String author) {
|
||||||
|
this.author = author;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getIsbn() {
|
||||||
|
return isbn;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setIsbn(int isbn) {
|
||||||
|
if (isbn < 0) {
|
||||||
|
throw new IllegalArgumentException("ISBN can't be negative");
|
||||||
|
}
|
||||||
|
this.isbn = isbn;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getBookDetails() {
|
||||||
|
return "author id: " + id + " author name: " + author + " ISBN: " + isbn;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
35
core-java-modules/core-java-lang-oop-others/src/test/java/com/baeldung/encapsulation/EncapsulationAndInformationHidingUnitTest.java
Normal file
35
core-java-modules/core-java-lang-oop-others/src/test/java/com/baeldung/encapsulation/EncapsulationAndInformationHidingUnitTest.java
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
package com.baeldung.encapsulation;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
public class EncapsulationAndInformationHidingUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUnencapsulatedClass_whenImplementationClassIsSeparate_thenReturnResult() {
|
||||||
|
Book myBook = new Book();
|
||||||
|
myBook.author = "J.K Rowlings";
|
||||||
|
myBook.isbn = 67890;
|
||||||
|
BookDetails details = new BookDetails();
|
||||||
|
String result = details.bookDetails(myBook);
|
||||||
|
assertEquals("author name: " + myBook.author + " ISBN: " + myBook.isbn, result);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenEncapsulatedClass_whenDataIsNotHidden_thenReturnResult() {
|
||||||
|
BookEncapsulation myBook = new BookEncapsulation("J.K Rowlings", 67890);
|
||||||
|
String result = myBook.getBookDetails();
|
||||||
|
assertEquals("author id: " + 1 + " author name: " + myBook.author + " ISBN: " + myBook.isbn, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenEncapsulatedClass_whenDataIsHidden_thenReturnResult() {
|
||||||
|
BookInformationHiding myBook = new BookInformationHiding("J.K Rowlings", 67890);
|
||||||
|
String result = myBook.getBookDetails();
|
||||||
|
assertEquals("author id: " + 1 + " author name: " + myBook.getAuthor() + " ISBN: " + myBook.getIsbn(), result);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
25
core-java-modules/core-java-networking/src/test/java/com/baeldung/networking/url/UrlUnitTest.java
25
core-java-modules/core-java-networking/src/test/java/com/baeldung/networking/url/UrlUnitTest.java
@ -2,10 +2,15 @@ package com.baeldung.networking.url;
|
|||||||
|
|
||||||
import static java.util.stream.Collectors.toList;
|
import static java.util.stream.Collectors.toList;
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertNotNull;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
import java.net.MalformedURLException;
|
import java.net.MalformedURLException;
|
||||||
|
import java.net.URI;
|
||||||
import java.net.URISyntaxException;
|
import java.net.URISyntaxException;
|
||||||
import java.net.URL;
|
import java.net.URL;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
import org.apache.http.client.utils.URIBuilder;
|
import org.apache.http.client.utils.URIBuilder;
|
||||||
@ -149,4 +154,24 @@ public class UrlUnitTest {
|
|||||||
assertEquals("http://baeldung.com:9090/articles?topic=java&version=8", url.toString());
|
assertEquals("http://baeldung.com:9090/articles?topic=java&version=8", url.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenURI_whenConvertingToURL_thenCorrect() throws IOException, URISyntaxException {
|
||||||
|
String aURIString = "http://courses.baeldung.com";
|
||||||
|
URI uri = new URI(aURIString);
|
||||||
|
URL url = uri.toURL();
|
||||||
|
assertNotNull(url);
|
||||||
|
assertEquals(aURIString, url.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPath_whenConvertingToURIAndThenURL_thenCorrect() throws IOException, URISyntaxException {
|
||||||
|
String finalPath = "file:/D:/baeldung/java-url";
|
||||||
|
Path path = Paths.get("/baeldung/java-url");
|
||||||
|
URI uri = path.toUri();
|
||||||
|
URL url = uri.toURL();
|
||||||
|
assertNotNull(url);
|
||||||
|
// Adapt the finalPath value to match your own path
|
||||||
|
// assertEquals(finalPath, url.toString());
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
@ -1,6 +1,8 @@
|
|||||||
package com.baeldung.integerToBinary;
|
package com.baeldung.integerToBinary;
|
||||||
|
|
||||||
|
import org.apache.commons.lang3.StringUtils;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
public class IntegerToBinaryUnitTest {
|
public class IntegerToBinaryUnitTest {
|
||||||
@ -24,4 +26,18 @@ public class IntegerToBinaryUnitTest {
|
|||||||
String binaryString = Integer.toString(n, 2);
|
String binaryString = Integer.toString(n, 2);
|
||||||
assertEquals("111", binaryString);
|
assertEquals("111", binaryString);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
@Test
|
||||||
|
public void givenAnInteger_whenFormatAndReplaceCalled_thenZeroPaddedBinaryString() {
|
||||||
|
int n = 7;
|
||||||
|
String binaryString = String.format("%8s", Integer.toBinaryString(n)).replace(" ", "0");
|
||||||
|
assertEquals("00000111", binaryString);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAnInteger_whenUsingApacheStringUtils_thenZeroPaddedBinaryString() {
|
||||||
|
int n = 7;
|
||||||
|
String binaryString = StringUtils.leftPad(Integer.toBinaryString(n), 8, "0");
|
||||||
|
assertEquals("00000111", binaryString);
|
||||||
|
}
|
||||||
|
}
|
@ -5,4 +5,5 @@
|
|||||||
- [Does Java Read Integers in Little Endian or Big Endian?](https://www.baeldung.com/java-integers-little-big-endian)
|
- [Does Java Read Integers in Little Endian or Big Endian?](https://www.baeldung.com/java-integers-little-big-endian)
|
||||||
- [How to Split an Integer Number Into Digits in Java](https://www.baeldung.com/java-integer-individual-digits)
|
- [How to Split an Integer Number Into Digits in Java](https://www.baeldung.com/java-integer-individual-digits)
|
||||||
- [Java Double vs. BigDecimal](https://www.baeldung.com/java-double-vs-bigdecimal)
|
- [Java Double vs. BigDecimal](https://www.baeldung.com/java-double-vs-bigdecimal)
|
||||||
|
- [Finding the Square Root of a BigInteger in Java](https://www.baeldung.com/java-find-square-root-biginteger)
|
||||||
- More articles: [[<-- prev]](../core-java-numbers-5)
|
- More articles: [[<-- prev]](../core-java-numbers-5)
|
||||||
|
28
core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/javadoublevsbigdecimal/BigDecimalConversionUnitTest.java
Normal file
28
core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/javadoublevsbigdecimal/BigDecimalConversionUnitTest.java
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
package com.baeldung.javadoublevsbigdecimal;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.math.RoundingMode;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
public class BigDecimalConversionUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenConvertingDoubleToBigDecimal_thenConversionIsCorrect() {
|
||||||
|
double doubleValue = 123.456;
|
||||||
|
BigDecimal bigDecimalValue = BigDecimal.valueOf(doubleValue);
|
||||||
|
BigDecimal expected = new BigDecimal("123.456").setScale(3, RoundingMode.HALF_UP);
|
||||||
|
assertEquals(expected, bigDecimalValue.setScale(3, RoundingMode.HALF_UP));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenDecimalPlacesGreaterThan15_whenConvertingBigDecimalToDouble_thenPrecisionIsLost() {
|
||||||
|
BigDecimal bigDecimalValue = new BigDecimal("789.1234567890123456");
|
||||||
|
double doubleValue = bigDecimalValue.doubleValue();
|
||||||
|
BigDecimal convertedBackToBigDecimal = BigDecimal.valueOf(doubleValue);
|
||||||
|
assertNotEquals(bigDecimalValue, convertedBackToBigDecimal);
|
||||||
|
}
|
||||||
|
}
|
42
core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/javadoublevsbigdecimal/BigDecimalUnitTest.java
Normal file
42
core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/javadoublevsbigdecimal/BigDecimalUnitTest.java
Normal file
@ -0,0 +1,42 @@
|
|||||||
|
package com.baeldung.javadoublevsbigdecimal;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.math.RoundingMode;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
public class BigDecimalUnitTest {
|
||||||
|
|
||||||
|
private BigDecimal bigDecimal1 = new BigDecimal("124567890.0987654321");
|
||||||
|
private BigDecimal bigDecimal2 = new BigDecimal("987654321.123456789");
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoBigDecimals_whenAdd_thenCorrect() {
|
||||||
|
BigDecimal expected = new BigDecimal("1112222211.2222222211");
|
||||||
|
BigDecimal actual = bigDecimal1.add(bigDecimal2);
|
||||||
|
assertEquals(expected, actual);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoBigDecimals_whenMultiply_thenCorrect() {
|
||||||
|
BigDecimal expected = new BigDecimal("123030014929277547.5030955772112635269");
|
||||||
|
BigDecimal actual = bigDecimal1.multiply(bigDecimal2);
|
||||||
|
assertEquals(expected, actual);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoBigDecimals_whenSubtract_thenCorrect() {
|
||||||
|
BigDecimal expected = new BigDecimal("-863086431.0246913569");
|
||||||
|
BigDecimal actual = bigDecimal1.subtract(bigDecimal2);
|
||||||
|
assertEquals(expected, actual);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoBigDecimals_whenDivide_thenCorrect() {
|
||||||
|
BigDecimal expected = new BigDecimal("0.13");
|
||||||
|
BigDecimal actual = bigDecimal1.divide(bigDecimal2, 2, RoundingMode.HALF_UP);
|
||||||
|
assertEquals(expected, actual);
|
||||||
|
}
|
||||||
|
}
|
15
core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/javadoublevsbigdecimal/JavaDoubleUnitTest.java
Normal file
15
core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/javadoublevsbigdecimal/JavaDoubleUnitTest.java
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
package com.baeldung.javadoublevsbigdecimal;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
public class JavaDoubleUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenDoubleLiteral_whenAssigningToDoubleVariable_thenValueIsNotExactlyEqual() {
|
||||||
|
double doubleValue = 0.1;
|
||||||
|
double epsilon = 0.0000000000000001;
|
||||||
|
assertEquals(0.1, doubleValue, epsilon);
|
||||||
|
}
|
||||||
|
}
|
@ -9,25 +9,21 @@ public class FloatDoubleConversionsTest {
|
|||||||
public void whenDoubleType_thenFloatTypeSuccess(){
|
public void whenDoubleType_thenFloatTypeSuccess(){
|
||||||
double interestRatesYearly = 13.333333333333334;
|
double interestRatesYearly = 13.333333333333334;
|
||||||
float interest = (float) interestRatesYearly;
|
float interest = (float) interestRatesYearly;
|
||||||
System.out.println(interest); //13.333333
|
Assert.assertEquals(13.333333f, interest, 0.000004f);
|
||||||
Assert.assertTrue(Float.class.isInstance(interest));//true
|
|
||||||
|
|
||||||
Double monthlyRates = 2.111111111111112;
|
Double monthlyRates = 2.111111111111112;
|
||||||
float rates = monthlyRates.floatValue();
|
float rates = monthlyRates.floatValue();
|
||||||
System.out.println(rates); //2.1111112
|
Assert.assertEquals(2.1111112f, rates, 0.00000013);
|
||||||
Assert.assertTrue(Float.class.isInstance(rates));//true
|
|
||||||
}
|
}
|
||||||
@Test
|
@Test
|
||||||
public void whenFloatType_thenDoubleTypeSuccess(){
|
public void whenFloatType_thenDoubleTypeSuccess(){
|
||||||
float gradeAverage =2.05f;
|
float gradeAverage =2.05f;
|
||||||
double average = gradeAverage;
|
double average = gradeAverage;
|
||||||
System.out.println(average); //2.049999952316284
|
Assert.assertEquals(2.05, average, 0.06);
|
||||||
Assert.assertTrue(Double.class.isInstance(average));//true
|
|
||||||
|
|
||||||
Float monthlyRates = 2.1111112f;
|
Float monthlyRates = 2.1111112f;
|
||||||
Double rates = monthlyRates.doubleValue();
|
Double rates = monthlyRates.doubleValue();
|
||||||
System.out.println(rates); //2.1111112
|
Assert.assertEquals(2.11111112, rates, 0.0000002);//true
|
||||||
Assert.assertTrue(Double.class.isInstance(rates));//true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
49
core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/floattobigdecimal/FloatToBigDecimalUnitTest.java
Normal file
49
core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/floattobigdecimal/FloatToBigDecimalUnitTest.java
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
package com.baeldung.floattobigdecimal;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
class FloatToBigDecimalUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenFloatComparedWithDifferentValues_thenCouldMatch() {
|
||||||
|
assertNotEquals(1.1f, 1.09f);
|
||||||
|
assertEquals(1.1f, 1.09999999f);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCreatedFromFloat_thenMatchesInternallyStoredValue() {
|
||||||
|
float floatToConvert = 1.10000002384185791015625f;
|
||||||
|
BigDecimal bdFromFloat = new BigDecimal(floatToConvert);
|
||||||
|
assertEquals("1.10000002384185791015625", bdFromFloat.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCreatedFromString_thenPreservesTheOriginal() {
|
||||||
|
BigDecimal bdFromString = new BigDecimal("1.1");
|
||||||
|
assertEquals("1.1", bdFromString.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCreatedFromFloatConvertedToString_thenFloatInternalValueGetsTruncated() {
|
||||||
|
String floatValue = Float.toString(1.10000002384185791015625f);
|
||||||
|
BigDecimal bdFromString = new BigDecimal(floatValue);
|
||||||
|
assertEquals("1.1", floatValue);
|
||||||
|
assertEquals("1.1", bdFromString.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCreatedByValueOf_thenFloatValueGetsTruncated() {
|
||||||
|
assertEquals("1.100000023841858", BigDecimal.valueOf(1.10000002384185791015625f).toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenDoubleConvertsFloatToString_thenFloatValueGetsTruncated() {
|
||||||
|
assertEquals("1.100000023841858", Double.toString(1.10000002384185791015625f));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
2
core-java-modules/core-java-reflection-3/README.md
Normal file
2
core-java-modules/core-java-reflection-3/README.md
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
### Relevant Articles:
|
||||||
|
- [Is Java Reflection Bad Practice?](https://www.baeldung.com/java-reflection-bad-practice)
|
78
core-java-modules/core-java-reflection-3/pom.xml
Normal file
78
core-java-modules/core-java-reflection-3/pom.xml
Normal file
@ -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-reflection-3</artifactId>
|
||||||
|
<name>core-java-reflection-3</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>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework</groupId>
|
||||||
|
<artifactId>spring-test</artifactId>
|
||||||
|
<version>${spring.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.reflections</groupId>
|
||||||
|
<artifactId>reflections</artifactId>
|
||||||
|
<version>${reflections.version}</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<finalName>core-java-reflection-3</finalName>
|
||||||
|
<resources>
|
||||||
|
<resource>
|
||||||
|
<directory>src/main/resources</directory>
|
||||||
|
<filtering>true</filtering>
|
||||||
|
</resource>
|
||||||
|
</resources>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>${maven-compiler-plugin.version}</version>
|
||||||
|
<configuration>
|
||||||
|
<source>${source.version}</source>
|
||||||
|
<target>${target.version}</target>
|
||||||
|
<compilerArgument>-parameters</compilerArgument>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.jacoco</groupId>
|
||||||
|
<artifactId>jacoco-maven-plugin</artifactId>
|
||||||
|
<version>0.8.8</version>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<goals>
|
||||||
|
<goal>prepare-agent</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
<execution>
|
||||||
|
<id>report</id>
|
||||||
|
<phase>prepare-package</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>report</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<reflections.version>0.9.12</reflections.version>
|
||||||
|
<source.version>1.8</source.version>
|
||||||
|
<target.version>1.8</target.version>
|
||||||
|
<spring.version>5.3.4</spring.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
</project>
|
11
core-java-modules/core-java-reflection-3/src/main/java/com/baeldung/reflection/disadvantages/encapsulation/MyClass.java
Normal file
11
core-java-modules/core-java-reflection-3/src/main/java/com/baeldung/reflection/disadvantages/encapsulation/MyClass.java
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
package com.baeldung.reflection.disadvantages.encapsulation;
|
||||||
|
|
||||||
|
public class MyClass {
|
||||||
|
|
||||||
|
private String veryPrivateField;
|
||||||
|
|
||||||
|
public MyClass() {
|
||||||
|
|
||||||
|
this.veryPrivateField = "Secret Information";
|
||||||
|
}
|
||||||
|
}
|
7
core-java-modules/core-java-reflection-3/src/main/java/com/baeldung/reflection/disadvantages/performance/BenchmarkRunner.java
Normal file
7
core-java-modules/core-java-reflection-3/src/main/java/com/baeldung/reflection/disadvantages/performance/BenchmarkRunner.java
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
package com.baeldung.reflection.disadvantages.performance;
|
||||||
|
|
||||||
|
public class BenchmarkRunner {
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
org.openjdk.jmh.Main.main(args);
|
||||||
|
}
|
||||||
|
}
|
29
core-java-modules/core-java-reflection-3/src/main/java/com/baeldung/reflection/disadvantages/performance/InitializationBenchmark.java
Normal file
29
core-java-modules/core-java-reflection-3/src/main/java/com/baeldung/reflection/disadvantages/performance/InitializationBenchmark.java
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
package com.baeldung.reflection.disadvantages.performance;
|
||||||
|
|
||||||
|
import org.openjdk.jmh.annotations.*;
|
||||||
|
|
||||||
|
import java.lang.reflect.Constructor;
|
||||||
|
import java.lang.reflect.InvocationTargetException;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
public class InitializationBenchmark {
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
@Fork(value = 1, warmups = 1)
|
||||||
|
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||||
|
@BenchmarkMode(Mode.AverageTime)
|
||||||
|
public void directInit() {
|
||||||
|
|
||||||
|
Person person = new Person("John", "Doe", 50);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
@Fork(value = 1, warmups = 1)
|
||||||
|
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||||
|
@BenchmarkMode(Mode.AverageTime)
|
||||||
|
public void reflectiveInit() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
|
||||||
|
|
||||||
|
Constructor<Person> constructor = Person.class.getDeclaredConstructor(String.class, String.class, Integer.class);
|
||||||
|
Person person = constructor.newInstance("John", "Doe", 50);
|
||||||
|
}
|
||||||
|
}
|
48
core-java-modules/core-java-reflection-3/src/main/java/com/baeldung/reflection/disadvantages/performance/MethodInvocationBenchmark.java
Normal file
48
core-java-modules/core-java-reflection-3/src/main/java/com/baeldung/reflection/disadvantages/performance/MethodInvocationBenchmark.java
Normal file
@ -0,0 +1,48 @@
|
|||||||
|
package com.baeldung.reflection.disadvantages.performance;
|
||||||
|
|
||||||
|
import org.openjdk.jmh.annotations.*;
|
||||||
|
|
||||||
|
import java.lang.reflect.InvocationTargetException;
|
||||||
|
import java.lang.reflect.Method;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
public class MethodInvocationBenchmark {
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
@Fork(value = 1, warmups = 1)
|
||||||
|
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||||
|
@BenchmarkMode(Mode.AverageTime)
|
||||||
|
public void directCall() {
|
||||||
|
|
||||||
|
directCall(new Person("John", "Doe", 50));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
@Fork(value = 1, warmups = 1)
|
||||||
|
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||||
|
@BenchmarkMode(Mode.AverageTime)
|
||||||
|
public void reflectiveCall() throws InvocationTargetException, NoSuchMethodException, IllegalAccessException {
|
||||||
|
|
||||||
|
reflectiveCall(new Person("John", "Doe", 50));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
private void directCall(Person person) {
|
||||||
|
|
||||||
|
person.getFirstName();
|
||||||
|
person.getLastName();
|
||||||
|
person.getAge();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void reflectiveCall(Person person) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
|
||||||
|
|
||||||
|
Method getFirstNameMethod = Person.class.getMethod("getFirstName");
|
||||||
|
getFirstNameMethod.invoke(person);
|
||||||
|
|
||||||
|
Method getLastNameMethod = Person.class.getMethod("getLastName");
|
||||||
|
getLastNameMethod.invoke(person);
|
||||||
|
|
||||||
|
Method getAgeMethod = Person.class.getMethod("getAge");
|
||||||
|
getAgeMethod.invoke(person);
|
||||||
|
}
|
||||||
|
}
|
38
core-java-modules/core-java-reflection-3/src/main/java/com/baeldung/reflection/disadvantages/performance/Person.java
Normal file
38
core-java-modules/core-java-reflection-3/src/main/java/com/baeldung/reflection/disadvantages/performance/Person.java
Normal file
@ -0,0 +1,38 @@
|
|||||||
|
package com.baeldung.reflection.disadvantages.performance;
|
||||||
|
|
||||||
|
public class Person {
|
||||||
|
|
||||||
|
private String firstName;
|
||||||
|
private String lastName;
|
||||||
|
private Integer age;
|
||||||
|
|
||||||
|
public Person(String firstName, String lastName, Integer age) {
|
||||||
|
this.firstName = firstName;
|
||||||
|
this.lastName = lastName;
|
||||||
|
this.age = age;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getFirstName() {
|
||||||
|
return firstName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setFirstName(String firstName) {
|
||||||
|
this.firstName = firstName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getLastName() {
|
||||||
|
return lastName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setLastName(String lastName) {
|
||||||
|
this.lastName = lastName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Integer getAge() {
|
||||||
|
return age;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setAge(Integer age) {
|
||||||
|
this.age = age;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,21 @@
|
|||||||
|
package com.baeldung.reflection.disadvantages.encapsulation;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.lang.reflect.Field;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
public class ReflectionEncapsulationUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPrivateField_whenUsingReflection_thenIsAccessible() throws IllegalAccessException, NoSuchFieldException {
|
||||||
|
MyClass myClassInstance = new MyClass();
|
||||||
|
|
||||||
|
Field privateField = MyClass.class.getDeclaredField("veryPrivateField");
|
||||||
|
privateField.setAccessible(true);
|
||||||
|
|
||||||
|
String accessedField = privateField.get(myClassInstance).toString();
|
||||||
|
assertEquals(accessedField, "Secret Information");
|
||||||
|
}
|
||||||
|
}
|
@ -7,7 +7,7 @@ import javax.net.ssl.SSLSocket;
|
|||||||
import javax.net.ssl.SSLSocketFactory;
|
import javax.net.ssl.SSLSocketFactory;
|
||||||
|
|
||||||
public class SecureConnection {
|
public class SecureConnection {
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
if (args.length != 2) {
|
if (args.length != 2) {
|
||||||
System.out.println("Use: SecureConnection host port");
|
System.out.println("Use: SecureConnection host port");
|
||||||
@ -20,20 +20,20 @@ public class SecureConnection {
|
|||||||
SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket(host, port);
|
SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket(host, port);
|
||||||
InputStream in = sslsocket.getInputStream();
|
InputStream in = sslsocket.getInputStream();
|
||||||
OutputStream out = sslsocket.getOutputStream();
|
OutputStream out = sslsocket.getOutputStream();
|
||||||
|
|
||||||
out.write(1);
|
out.write(1);
|
||||||
|
|
||||||
while (in.available() > 0) {
|
while (in.available() > 0) {
|
||||||
System.out.print(in.read());
|
System.out.print(in.read());
|
||||||
}
|
}
|
||||||
|
|
||||||
System.out.println("Secured connection performed successfully");
|
System.out.println("Secured connection performed successfully");
|
||||||
|
|
||||||
} catch (Exception exception) {
|
} catch (Exception exception) {
|
||||||
exception.printStackTrace();
|
exception.printStackTrace();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the host from arguments
|
* Get the host from arguments
|
||||||
* @param args the arguments
|
* @param args the arguments
|
||||||
@ -42,7 +42,7 @@ public class SecureConnection {
|
|||||||
private static String getHost(String[] args) {
|
private static String getHost(String[] args) {
|
||||||
return args[0];
|
return args[0];
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the port from arguments
|
* Get the port from arguments
|
||||||
* @param args the arguments
|
* @param args the arguments
|
||||||
|
@ -15,10 +15,8 @@ public class SimpleClient {
|
|||||||
SocketFactory factory = SSLSocketFactory.getDefault();
|
SocketFactory factory = SSLSocketFactory.getDefault();
|
||||||
|
|
||||||
try (Socket connection = factory.createSocket(host, port)) {
|
try (Socket connection = factory.createSocket(host, port)) {
|
||||||
((SSLSocket) connection).setEnabledCipherSuites(
|
((SSLSocket) connection).setEnabledCipherSuites(new String[] { "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256" });
|
||||||
new String[] { "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256"});
|
((SSLSocket) connection).setEnabledProtocols(new String[] { "TLSv1.2" });
|
||||||
((SSLSocket) connection).setEnabledProtocols(
|
|
||||||
new String[] { "TLSv1.2"});
|
|
||||||
SSLParameters sslParams = new SSLParameters();
|
SSLParameters sslParams = new SSLParameters();
|
||||||
sslParams.setEndpointIdentificationAlgorithm("HTTPS");
|
sslParams.setEndpointIdentificationAlgorithm("HTTPS");
|
||||||
((SSLSocket) connection).setSSLParameters(sslParams);
|
((SSLSocket) connection).setSSLParameters(sslParams);
|
||||||
@ -28,6 +26,7 @@ public class SimpleClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public static void main(String[] args) throws IOException {
|
public static void main(String[] args) throws IOException {
|
||||||
|
System.setProperty("javax.net.debug", "ssl:handshake");
|
||||||
System.out.println(startClient("localhost", 8443));
|
System.out.println(startClient("localhost", 8443));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -14,11 +14,10 @@ public class SimpleServer {
|
|||||||
ServerSocketFactory factory = SSLServerSocketFactory.getDefault();
|
ServerSocketFactory factory = SSLServerSocketFactory.getDefault();
|
||||||
|
|
||||||
try (ServerSocket listener = factory.createServerSocket(port)) {
|
try (ServerSocket listener = factory.createServerSocket(port)) {
|
||||||
|
System.setProperty("javax.net.debug", "ssl:handshake");
|
||||||
((SSLServerSocket) listener).setNeedClientAuth(true);
|
((SSLServerSocket) listener).setNeedClientAuth(true);
|
||||||
((SSLServerSocket) listener).setEnabledCipherSuites(
|
((SSLServerSocket) listener).setEnabledCipherSuites(new String[] { "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256" });
|
||||||
new String[] { "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256"});
|
((SSLServerSocket) listener).setEnabledProtocols(new String[] { "TLSv1.2" });
|
||||||
((SSLServerSocket) listener).setEnabledProtocols(
|
|
||||||
new String[] { "TLSv1.2"});
|
|
||||||
while (true) {
|
while (true) {
|
||||||
try (Socket socket = listener.accept()) {
|
try (Socket socket = listener.accept()) {
|
||||||
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
|
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
|
||||||
@ -29,6 +28,7 @@ public class SimpleServer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public static void main(String[] args) throws IOException {
|
public static void main(String[] args) throws IOException {
|
||||||
|
System.setProperty("javax.net.debug", "ssl:handshake");
|
||||||
startServer(8443);
|
startServer(8443);
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -4,12 +4,9 @@ This module contains articles about the Stream API in Java.
|
|||||||
|
|
||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
- [The Java 8 Stream API Tutorial](https://www.baeldung.com/java-8-streams)
|
- [The Java 8 Stream API Tutorial](https://www.baeldung.com/java-8-streams)
|
||||||
- [Introduction to Java 8 Streams](https://www.baeldung.com/java-8-streams-introduction)
|
|
||||||
- [Java 8 Stream findFirst() vs. findAny()](https://www.baeldung.com/java-stream-findfirst-vs-findany)
|
- [Java 8 Stream findFirst() vs. findAny()](https://www.baeldung.com/java-stream-findfirst-vs-findany)
|
||||||
- [Guide to Stream.reduce()](https://www.baeldung.com/java-stream-reduce)
|
|
||||||
- [Java IntStream Conversions](https://www.baeldung.com/java-intstream-convert)
|
- [Java IntStream Conversions](https://www.baeldung.com/java-intstream-convert)
|
||||||
- [Java 8 Streams peek() API](https://www.baeldung.com/java-streams-peek-api)
|
- [Java 8 Streams peek() API](https://www.baeldung.com/java-streams-peek-api)
|
||||||
- [Working With Maps Using Streams](https://www.baeldung.com/java-maps-streams)
|
|
||||||
- [Collect a Java Stream to an Immutable Collection](https://www.baeldung.com/java-stream-immutable-collection)
|
- [Collect a Java Stream to an Immutable Collection](https://www.baeldung.com/java-stream-immutable-collection)
|
||||||
- [How to Add a Single Element to a Stream](https://www.baeldung.com/java-stream-append-prepend)
|
- [How to Add a Single Element to a Stream](https://www.baeldung.com/java-stream-append-prepend)
|
||||||
- [Operating on and Removing an Item from Stream](https://www.baeldung.com/java-use-remove-item-stream)
|
- [Operating on and Removing an Item from Stream](https://www.baeldung.com/java-use-remove-item-stream)
|
||||||
|
2
core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/Java8StreamApiUnitTest.java
2
core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/Java8StreamApiUnitTest.java
@ -1,6 +1,7 @@
|
|||||||
package com.baeldung.streams;
|
package com.baeldung.streams;
|
||||||
|
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
|
import org.junit.Ignore;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
@ -37,6 +38,7 @@ public class Java8StreamApiUnitTest {
|
|||||||
assertEquals(list.size() - 1, size);
|
assertEquals(list.size() - 1, size);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Ignore
|
||||||
@Test
|
@Test
|
||||||
public void checkOrder_whenChangeQuantityOfMethodCalls_thenCorrect() {
|
public void checkOrder_whenChangeQuantityOfMethodCalls_thenCorrect() {
|
||||||
|
|
||||||
|
@ -2,8 +2,7 @@
|
|||||||
|
|
||||||
This module contains articles about the Stream API in Java.
|
This module contains articles about the Stream API in Java.
|
||||||
|
|
||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
- [The Difference Between map() and flatMap()](https://www.baeldung.com/java-difference-map-and-flatmap)
|
|
||||||
- [How to Use if/else Logic in Java 8 Streams](https://www.baeldung.com/java-8-streams-if-else-logic)
|
- [How to Use if/else Logic in Java 8 Streams](https://www.baeldung.com/java-8-streams-if-else-logic)
|
||||||
- [The Difference Between Collection.stream().forEach() and Collection.forEach()](https://www.baeldung.com/java-collection-stream-foreach)
|
- [The Difference Between Collection.stream().forEach() and Collection.forEach()](https://www.baeldung.com/java-collection-stream-foreach)
|
||||||
- [Primitive Type Streams in Java 8](https://www.baeldung.com/java-8-primitive-streams)
|
- [Primitive Type Streams in Java 8](https://www.baeldung.com/java-8-primitive-streams)
|
||||||
@ -12,5 +11,4 @@ This module contains articles about the Stream API in Java.
|
|||||||
- [Should We Close a Java Stream?](https://www.baeldung.com/java-stream-close)
|
- [Should We Close a Java Stream?](https://www.baeldung.com/java-stream-close)
|
||||||
- [Returning Stream vs. Collection](https://www.baeldung.com/java-return-stream-collection)
|
- [Returning Stream vs. Collection](https://www.baeldung.com/java-return-stream-collection)
|
||||||
- [Convert a Java Enumeration Into a Stream](https://www.baeldung.com/java-enumeration-to-stream)
|
- [Convert a Java Enumeration Into a Stream](https://www.baeldung.com/java-enumeration-to-stream)
|
||||||
- [When to Use a Parallel Stream in Java](https://www.baeldung.com/java-when-to-use-parallel-stream)
|
|
||||||
- More articles: [[<-- prev>]](/../core-java-streams-2)
|
- More articles: [[<-- prev>]](/../core-java-streams-2)
|
||||||
|
@ -3,3 +3,4 @@
|
|||||||
- [Working With Empty Stream in Java](https://www.baeldung.com/java-empty-stream)
|
- [Working With Empty Stream in Java](https://www.baeldung.com/java-empty-stream)
|
||||||
- [Aggregate Runtime Exceptions in Java Streams](https://www.baeldung.com/java-streams-aggregate-exceptions)
|
- [Aggregate Runtime Exceptions in Java Streams](https://www.baeldung.com/java-streams-aggregate-exceptions)
|
||||||
- [Streams vs. Loops in Java](https://www.baeldung.com/java-streams-vs-loops)
|
- [Streams vs. Loops in Java](https://www.baeldung.com/java-streams-vs-loops)
|
||||||
|
- [Partition a Stream in Java](https://www.baeldung.com/java-partition-stream)
|
||||||
|
32
core-java-modules/core-java-streams-5/src/main/java/com/baeldung/skippingelements/SkippingCollector.java
Normal file
32
core-java-modules/core-java-streams-5/src/main/java/com/baeldung/skippingelements/SkippingCollector.java
Normal file
@ -0,0 +1,32 @@
|
|||||||
|
package com.baeldung.skippingelements;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.function.BinaryOperator;
|
||||||
|
import java.util.stream.Collector;
|
||||||
|
|
||||||
|
class SkippingCollector {
|
||||||
|
private static final BinaryOperator<SkippingCollector> IGNORE_COMBINE = (a, b) -> a;
|
||||||
|
private final int skip;
|
||||||
|
private final List<String> list = new ArrayList<>();
|
||||||
|
private int currentIndex = 0;
|
||||||
|
private SkippingCollector(int skip) {
|
||||||
|
this.skip = skip;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void accept(String item) {
|
||||||
|
final int index = ++currentIndex % skip;
|
||||||
|
if (index == 0)
|
||||||
|
list.add(item);
|
||||||
|
}
|
||||||
|
private List<String> getResult() {
|
||||||
|
return list;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Collector<String, SkippingCollector, List<String>> collector(int skip) {
|
||||||
|
return Collector.of(() -> new SkippingCollector(skip),
|
||||||
|
SkippingCollector::accept,
|
||||||
|
IGNORE_COMBINE,
|
||||||
|
SkippingCollector::getResult);
|
||||||
|
}
|
||||||
|
}
|
65
core-java-modules/core-java-streams-5/src/main/java/com/baeldung/skippingelements/SkippingElements.java
Normal file
65
core-java-modules/core-java-streams-5/src/main/java/com/baeldung/skippingelements/SkippingElements.java
Normal file
@ -0,0 +1,65 @@
|
|||||||
|
package com.baeldung.skippingelements;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Iterator;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.IntStream;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
public class SkippingElements {
|
||||||
|
|
||||||
|
private SkippingElements() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<String> skipNthElementInListWithFilter(List<String> sourceList, int n) {
|
||||||
|
return IntStream.range(0, sourceList.size())
|
||||||
|
.filter(s -> (s + 1) % n == 0)
|
||||||
|
.mapToObj(sourceList::get)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<String> skipNthElementInListWithIterate(List<String> sourceList, int n) {
|
||||||
|
int limit = sourceList.size() / n;
|
||||||
|
return IntStream.iterate(n - 1, i -> (i + n))
|
||||||
|
.limit(limit)
|
||||||
|
.mapToObj(sourceList::get)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<String> skipNthElementInListWithSublist(List<String> sourceList, int n) {
|
||||||
|
int limit = sourceList.size() / n;
|
||||||
|
return Stream.iterate(sourceList, s -> s.subList(n, s.size()))
|
||||||
|
.limit(limit)
|
||||||
|
.map(s -> s.get(n - 1))
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<String> skipNthElementInListWithFor(List<String> sourceList, int n) {
|
||||||
|
List<String> result = new ArrayList<>();
|
||||||
|
for (int i = n - 1; i < sourceList.size(); i += n) {
|
||||||
|
result.add(sourceList.get(i));
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<String> skipNthElementInListWithIterator(Stream<String> sourceStream, int n) {
|
||||||
|
List<String> result = new ArrayList<>();
|
||||||
|
final Iterator<String> iterator = sourceStream.iterator();
|
||||||
|
int count = 0;
|
||||||
|
while (iterator.hasNext()) {
|
||||||
|
if (count % n == n - 1) {
|
||||||
|
result.add(iterator.next());
|
||||||
|
} else {
|
||||||
|
iterator.next();
|
||||||
|
}
|
||||||
|
++count;
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<String> skipNthElementInStreamWithCollector(Stream<String> sourceStream, int n) {
|
||||||
|
return sourceStream.collect(SkippingCollector.collector(n));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
114
core-java-modules/core-java-streams-5/src/test/java/com/baeldung/skippingelements/SkippingElementsUnitTest.java
Normal file
114
core-java-modules/core-java-streams-5/src/test/java/com/baeldung/skippingelements/SkippingElementsUnitTest.java
Normal file
@ -0,0 +1,114 @@
|
|||||||
|
package com.baeldung.skippingelements;
|
||||||
|
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
import org.junit.jupiter.params.ParameterizedTest;
|
||||||
|
import org.junit.jupiter.params.provider.Arguments;
|
||||||
|
import org.junit.jupiter.params.provider.MethodSource;
|
||||||
|
|
||||||
|
class SkippingElementsUnitTest {
|
||||||
|
|
||||||
|
private static Stream<Arguments> testSource() {
|
||||||
|
return Stream.of(
|
||||||
|
Arguments.of(
|
||||||
|
List.of("One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen",
|
||||||
|
"Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen", "Twenty", "Twenty One", "Twenty Two",
|
||||||
|
"Twenty Three", "Twenty Four", "Twenty Five", "Twenty Six", "Twenty Seven", "Twenty Eight", "Twenty Nine", "Thirty",
|
||||||
|
"Thirty One", "Thirty Two", "Thirty Three"),
|
||||||
|
List.of("Three", "Six", "Nine", "Twelve", "Fifteen", "Eighteen", "Twenty One", "Twenty Four", "Twenty Seven", "Thirty", "Thirty Three"),
|
||||||
|
3),
|
||||||
|
Arguments.of(
|
||||||
|
List.of("One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen",
|
||||||
|
"Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen", "Twenty", "Twenty One", "Twenty Two",
|
||||||
|
"Twenty Three", "Twenty Four", "Twenty Five", "Twenty Six", "Twenty Seven", "Twenty Eight", "Twenty Nine", "Thirty",
|
||||||
|
"Thirty One", "Thirty Two", "Thirty Three"),
|
||||||
|
List.of("Five", "Ten", "Fifteen", "Twenty", "Twenty Five", "Thirty"),
|
||||||
|
5),
|
||||||
|
Arguments.of(
|
||||||
|
List.of("One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen",
|
||||||
|
"Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen", "Twenty", "Twenty One", "Twenty Two",
|
||||||
|
"Twenty Three", "Twenty Four", "Twenty Five", "Twenty Six", "Twenty Seven", "Twenty Eight", "Twenty Nine", "Thirty",
|
||||||
|
"Thirty One", "Thirty Two", "Thirty Three"),
|
||||||
|
List.of("One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen",
|
||||||
|
"Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen", "Twenty", "Twenty One", "Twenty Two",
|
||||||
|
"Twenty Three", "Twenty Four", "Twenty Five", "Twenty Six", "Twenty Seven", "Twenty Eight", "Twenty Nine", "Thirty",
|
||||||
|
"Thirty One", "Thirty Two", "Thirty Three"),
|
||||||
|
1),
|
||||||
|
Arguments.of(
|
||||||
|
List.of("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"),
|
||||||
|
List.of("Wednesday", "Saturday"),
|
||||||
|
3),
|
||||||
|
Arguments.of(
|
||||||
|
List.of("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"),
|
||||||
|
List.of("Friday"),
|
||||||
|
5),
|
||||||
|
Arguments.of(
|
||||||
|
List.of("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"),
|
||||||
|
List.of("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"),
|
||||||
|
1),
|
||||||
|
Arguments.of(
|
||||||
|
List.of("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November",
|
||||||
|
"December"),
|
||||||
|
List.of("March", "June", "September", "December"),
|
||||||
|
3),
|
||||||
|
Arguments.of(
|
||||||
|
List.of("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November",
|
||||||
|
"December"),
|
||||||
|
List.of("May", "October"),
|
||||||
|
5),
|
||||||
|
Arguments.of(
|
||||||
|
List.of("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November",
|
||||||
|
"December"),
|
||||||
|
List.of("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November",
|
||||||
|
"December"),
|
||||||
|
1)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ParameterizedTest
|
||||||
|
@MethodSource("testSource")
|
||||||
|
void givenListSkipNthElementInListWithFilterTestShouldFilterNthElement(List<String> input, List<String> expected, int n) {
|
||||||
|
final List<String> actual = SkippingElements.skipNthElementInListWithFilter(input, n);
|
||||||
|
assertEquals(expected, actual);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ParameterizedTest
|
||||||
|
@MethodSource("testSource")
|
||||||
|
void givenListSkipNthElementInListWithIterateTestShouldFilterNthElement(List<String> input, List<String> expected, int n) {
|
||||||
|
final List<String> actual = SkippingElements.skipNthElementInListWithIterate(input, n);
|
||||||
|
assertEquals(expected, actual);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ParameterizedTest
|
||||||
|
@MethodSource("testSource")
|
||||||
|
void givenListSkipNthElementInListWithSublistTestShouldFilterNthElement(List<String> input, List<String> expected, int n) {
|
||||||
|
final List<String> actual = SkippingElements.skipNthElementInListWithSublist(input, n);
|
||||||
|
assertEquals(expected, actual);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ParameterizedTest
|
||||||
|
@MethodSource("testSource")
|
||||||
|
void givenListSkipNthElementInListWithForTestShouldFilterNthElement(List<String> input, List<String> expected, int n) {
|
||||||
|
final List<String> actual = SkippingElements.skipNthElementInListWithFor(input, n);
|
||||||
|
assertEquals(expected, actual);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ParameterizedTest
|
||||||
|
@MethodSource("testSource")
|
||||||
|
void givenListSkipNthElementInStreamWithIteratorTestShouldFilterNthElement(List<String> input, List<String> expected, int n) {
|
||||||
|
final Stream<String> inputStream = input.stream();
|
||||||
|
final List<String> actual = SkippingElements.skipNthElementInListWithIterator(inputStream, n);
|
||||||
|
assertEquals(expected, actual);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ParameterizedTest
|
||||||
|
@MethodSource("testSource")
|
||||||
|
void givenListSkipNthElementInStreamWithCollectorShouldFilterNthElement(List<String> input, List<String> expected, int n) {
|
||||||
|
final Stream<String> inputStream = input.stream();
|
||||||
|
final List<String> actual = SkippingElements.skipNthElementInStreamWithCollector(inputStream, n);
|
||||||
|
assertEquals(expected, actual);
|
||||||
|
}
|
||||||
|
}
|
14
core-java-modules/core-java-streams-simple/README.md
Normal file
14
core-java-modules/core-java-streams-simple/README.md
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
## Java Streams Ebook
|
||||||
|
|
||||||
|
This module contains articles about Streams that are part of the Java Streams Ebook.
|
||||||
|
|
||||||
|
### Relevant Articles
|
||||||
|
|
||||||
|
- [Introduction to Java 8 Streams](https://www.baeldung.com/java-8-streams-introduction)
|
||||||
|
- [Guide to Java 8’s Collectors](https://www.baeldung.com/java-8-collectors)
|
||||||
|
- [Java Stream Filter with Lambda Expression](https://www.baeldung.com/java-stream-filter-lambda)
|
||||||
|
- [Working With Maps Using Streams](https://www.baeldung.com/java-maps-streams)
|
||||||
|
- [The Difference Between map() and flatMap()](https://www.baeldung.com/java-difference-map-and-flatmap)
|
||||||
|
- [When to Use a Parallel Stream in Java](https://www.baeldung.com/java-when-to-use-parallel-stream)
|
||||||
|
- [Guide to Java 8 groupingBy Collector](https://www.baeldung.com/java-groupingby-collector)
|
||||||
|
- [Guide to Stream.reduce()](https://www.baeldung.com/java-stream-reduce)
|
52
core-java-modules/core-java-streams-simple/pom.xml
Normal file
52
core-java-modules/core-java-streams-simple/pom.xml
Normal file
@ -0,0 +1,52 @@
|
|||||||
|
<?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-streams-simple</artifactId>
|
||||||
|
<name>core-java-streams-simple</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>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.pivovarit</groupId>
|
||||||
|
<artifactId>throwing-function</artifactId>
|
||||||
|
<version>${throwing-function.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.commons</groupId>
|
||||||
|
<artifactId>commons-lang3</artifactId>
|
||||||
|
<version>${commons-lang3.version}</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<finalName>core-java-streams-simple</finalName>
|
||||||
|
<resources>
|
||||||
|
<resource>
|
||||||
|
<directory>src/main/resources</directory>
|
||||||
|
<filtering>true</filtering>
|
||||||
|
</resource>
|
||||||
|
</resources>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<throwing-function.version>1.5.1</throwing-function.version>
|
||||||
|
<maven.compiler.source.version>17</maven.compiler.source.version>
|
||||||
|
<maven.compiler.target.version>17</maven.compiler.target.version>
|
||||||
|
<maven.compiler.release>17</maven.compiler.release>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
</project>
|
56
core-java-modules/core-java-streams-simple/src/main/java/com/baeldung/streams/filter/Customer.java
Normal file
56
core-java-modules/core-java-streams-simple/src/main/java/com/baeldung/streams/filter/Customer.java
Normal file
@ -0,0 +1,56 @@
|
|||||||
|
package com.baeldung.streams.filter;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.HttpURLConnection;
|
||||||
|
import java.net.URL;
|
||||||
|
|
||||||
|
import javax.net.ssl.HttpsURLConnection;
|
||||||
|
|
||||||
|
public class Customer {
|
||||||
|
private String name;
|
||||||
|
private int points;
|
||||||
|
private String profilePhotoUrl;
|
||||||
|
|
||||||
|
public Customer(String name, int points) {
|
||||||
|
this(name, points, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
public Customer(String name, int points, String profilePhotoUrl) {
|
||||||
|
this.name = name;
|
||||||
|
this.points = points;
|
||||||
|
this.profilePhotoUrl = profilePhotoUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getPoints() {
|
||||||
|
return points;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean hasOver(int points) {
|
||||||
|
return this.points > points;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean hasOverHundredPoints() {
|
||||||
|
return this.points > 100;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean hasValidProfilePhoto() throws IOException {
|
||||||
|
URL url = new URL(this.profilePhotoUrl);
|
||||||
|
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
|
||||||
|
return connection.getResponseCode() == HttpURLConnection.HTTP_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean hasValidProfilePhotoWithoutCheckedException() {
|
||||||
|
try {
|
||||||
|
URL url = new URL(this.profilePhotoUrl);
|
||||||
|
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
|
||||||
|
return connection.getResponseCode() == HttpURLConnection.HTTP_OK;
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.java_16_features.groupingby;
|
package com.baeldung.streams.groupingby;
|
||||||
|
|
||||||
import java.util.IntSummaryStatistics;
|
import java.util.IntSummaryStatistics;
|
||||||
|
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.java_16_features.groupingby;
|
package com.baeldung.streams.groupingby;
|
||||||
|
|
||||||
public enum BlogPostType {
|
public enum BlogPostType {
|
||||||
NEWS, REVIEW, GUIDE
|
NEWS, REVIEW, GUIDE
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.java_16_features.groupingby;
|
package com.baeldung.streams.groupingby;
|
||||||
|
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
|
|
@ -1,8 +1,7 @@
|
|||||||
package com.baeldung.reduce.application;
|
package com.baeldung.streams.reduce.application;
|
||||||
|
|
||||||
|
import com.baeldung.streams.reduce.entities.User;
|
||||||
|
|
||||||
import com.baeldung.reduce.entities.User;
|
|
||||||
import com.baeldung.reduce.utilities.NumberUtils;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
@ -1,6 +1,6 @@
|
|||||||
package com.baeldung.reduce.benchmarks;
|
package com.baeldung.streams.reduce.benchmarks;
|
||||||
|
|
||||||
import com.baeldung.reduce.entities.User;
|
import com.baeldung.streams.reduce.entities.User;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import org.openjdk.jmh.annotations.Benchmark;
|
import org.openjdk.jmh.annotations.Benchmark;
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.reduce.entities;
|
package com.baeldung.streams.reduce.entities;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.reduce.entities;
|
package com.baeldung.streams.reduce.entities;
|
||||||
|
|
||||||
public class Review {
|
public class Review {
|
||||||
|
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.reduce.entities;
|
package com.baeldung.streams.reduce.entities;
|
||||||
|
|
||||||
public class User {
|
public class User {
|
||||||
|
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.reduce.utilities;
|
package com.baeldung.streams.reduce.utilities;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.function.BiFunction;
|
import java.util.function.BiFunction;
|
@ -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>
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.collectors;
|
package com.baeldung.streams.collectors;
|
||||||
|
|
||||||
import com.google.common.collect.ImmutableList;
|
import com.google.common.collect.ImmutableList;
|
||||||
import com.google.common.collect.ImmutableSet;
|
import com.google.common.collect.ImmutableSet;
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.stream.filter;
|
package com.baeldung.streams.filter;
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import com.pivovarit.function.ThrowingPredicate;
|
import com.pivovarit.function.ThrowingPredicate;
|
||||||
@ -14,10 +14,10 @@ import java.util.stream.Stream;
|
|||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
|
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
|
||||||
|
|
||||||
public class StreamFilterUnitTest {
|
class StreamFilterUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenListOfCustomers_whenFilterByPoints_thenGetTwo() {
|
void givenListOfCustomers_whenFilterByPoints_thenGetTwo() {
|
||||||
Customer john = new Customer("John P.", 15);
|
Customer john = new Customer("John P.", 15);
|
||||||
Customer sarah = new Customer("Sarah M.", 200);
|
Customer sarah = new Customer("Sarah M.", 200);
|
||||||
Customer charles = new Customer("Charles B.", 150);
|
Customer charles = new Customer("Charles B.", 150);
|
||||||
@ -53,7 +53,7 @@ public class StreamFilterUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenListOfCustomers_whenFilterByMethodReference_thenGetTwo() {
|
void givenListOfCustomers_whenFilterByMethodReference_thenGetTwo() {
|
||||||
Customer john = new Customer("John P.", 15);
|
Customer john = new Customer("John P.", 15);
|
||||||
Customer sarah = new Customer("Sarah M.", 200);
|
Customer sarah = new Customer("Sarah M.", 200);
|
||||||
Customer charles = new Customer("Charles B.", 150);
|
Customer charles = new Customer("Charles B.", 150);
|
||||||
@ -70,7 +70,7 @@ public class StreamFilterUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenListOfCustomersWithOptional_whenFilterBy100Points_thenGetTwo() {
|
void givenListOfCustomersWithOptional_whenFilterBy100Points_thenGetTwo() {
|
||||||
Optional<Customer> john = Optional.of(new Customer("John P.", 15));
|
Optional<Customer> john = Optional.of(new Customer("John P.", 15));
|
||||||
Optional<Customer> sarah = Optional.of(new Customer("Sarah M.", 200));
|
Optional<Customer> sarah = Optional.of(new Customer("Sarah M.", 200));
|
||||||
Optional<Customer> mary = Optional.of(new Customer("Mary T.", 300));
|
Optional<Customer> mary = Optional.of(new Customer("Mary T.", 300));
|
||||||
@ -89,7 +89,7 @@ public class StreamFilterUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenListOfCustomers_whenFilterWithCustomHandling_thenThrowException() {
|
void givenListOfCustomers_whenFilterWithCustomHandling_thenThrowException() {
|
||||||
Customer john = new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e");
|
Customer john = new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e");
|
||||||
Customer sarah = new Customer("Sarah M.", 200);
|
Customer sarah = new Customer("Sarah M.", 200);
|
||||||
Customer charles = new Customer("Charles B.", 150);
|
Customer charles = new Customer("Charles B.", 150);
|
||||||
@ -103,7 +103,7 @@ public class StreamFilterUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenListOfCustomers_whenFilterWithThrowingFunction_thenThrowException() {
|
void givenListOfCustomers_whenFilterWithThrowingFunction_thenThrowException() {
|
||||||
Customer john = new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e");
|
Customer john = new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e");
|
||||||
Customer sarah = new Customer("Sarah M.", 200);
|
Customer sarah = new Customer("Sarah M.", 200);
|
||||||
Customer charles = new Customer("Charles B.", 150);
|
Customer charles = new Customer("Charles B.", 150);
|
@ -1,6 +1,7 @@
|
|||||||
package com.baeldung.streams.flatmap.map;
|
package com.baeldung.streams.flatmap.map;
|
||||||
|
|
||||||
import org.junit.Test;
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
@ -10,12 +11,12 @@ import java.util.stream.Collectors;
|
|||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
import static java.util.Arrays.asList;
|
import static java.util.Arrays.asList;
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
|
|
||||||
public class Java8MapAndFlatMapUnitTest {
|
|
||||||
|
class Java8MapAndFlatMapUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenStream_whenCalledMap_thenProduceList() {
|
void givenStream_whenCalledMap_thenProduceList() {
|
||||||
List<String> myList = Stream.of("a", "b")
|
List<String> myList = Stream.of("a", "b")
|
||||||
.map(String::toUpperCase)
|
.map(String::toUpperCase)
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
@ -23,7 +24,7 @@ public class Java8MapAndFlatMapUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenStream_whenCalledFlatMap_thenProduceFlattenedList() throws Exception {
|
void givenStream_whenCalledFlatMap_thenProduceFlattenedList() {
|
||||||
List<List<String>> list = Arrays.asList(Arrays.asList("a"), Arrays.asList("b"));
|
List<List<String>> list = Arrays.asList(Arrays.asList("a"), Arrays.asList("b"));
|
||||||
System.out.println(list);
|
System.out.println(list);
|
||||||
|
|
||||||
@ -33,13 +34,13 @@ public class Java8MapAndFlatMapUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenOptional_whenCalledMap_thenProduceOptional() {
|
void givenOptional_whenCalledMap_thenProduceOptional() {
|
||||||
Optional<String> s = Optional.of("test");
|
Optional<String> s = Optional.of("test");
|
||||||
assertEquals(Optional.of("TEST"), s.map(String::toUpperCase));
|
assertEquals(Optional.of("TEST"), s.map(String::toUpperCase));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenOptional_whenCalledFlatMap_thenProduceFlattenedOptional() {
|
void givenOptional_whenCalledFlatMap_thenProduceFlattenedOptional() {
|
||||||
assertEquals(Optional.of(Optional.of("STRING")), Optional.of("string")
|
assertEquals(Optional.of(Optional.of("STRING")), Optional.of("string")
|
||||||
.map(s -> Optional.of("STRING")));
|
.map(s -> Optional.of("STRING")));
|
||||||
|
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.java_16_features.groupingby;
|
package com.baeldung.streams.groupingby;
|
||||||
|
|
||||||
import static java.util.Comparator.comparingInt;
|
import static java.util.Comparator.comparingInt;
|
||||||
import static java.util.stream.Collectors.averagingInt;
|
import static java.util.stream.Collectors.averagingInt;
|
||||||
@ -33,13 +33,13 @@ import org.apache.commons.lang3.tuple.ImmutablePair;
|
|||||||
import org.apache.commons.lang3.tuple.Pair;
|
import org.apache.commons.lang3.tuple.Pair;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
public class JavaGroupingByCollectorUnitTest {
|
class JavaGroupingByCollectorUnitTest {
|
||||||
|
|
||||||
private static final List<BlogPost> posts = Arrays.asList(new BlogPost("News item 1", "Author 1", BlogPostType.NEWS, 15), new BlogPost("Tech review 1", "Author 2", BlogPostType.REVIEW, 5),
|
private static final List<BlogPost> posts = Arrays.asList(new BlogPost("News item 1", "Author 1", BlogPostType.NEWS, 15), new BlogPost("Tech review 1", "Author 2", BlogPostType.REVIEW, 5),
|
||||||
new BlogPost("Programming guide", "Author 1", BlogPostType.GUIDE, 20), new BlogPost("News item 2", "Author 2", BlogPostType.NEWS, 35), new BlogPost("Tech review 2", "Author 1", BlogPostType.REVIEW, 15));
|
new BlogPost("Programming guide", "Author 1", BlogPostType.GUIDE, 20), new BlogPost("News item 2", "Author 2", BlogPostType.NEWS, 35), new BlogPost("Tech review 2", "Author 1", BlogPostType.REVIEW, 15));
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenAListOfPosts_whenGroupedByType_thenGetAMapBetweenTypeAndPosts() {
|
void givenAListOfPosts_whenGroupedByType_thenGetAMapBetweenTypeAndPosts() {
|
||||||
Map<BlogPostType, List<BlogPost>> postsPerType = posts.stream()
|
Map<BlogPostType, List<BlogPost>> postsPerType = posts.stream()
|
||||||
.collect(groupingBy(BlogPost::getType));
|
.collect(groupingBy(BlogPost::getType));
|
||||||
|
|
||||||
@ -52,7 +52,7 @@ public class JavaGroupingByCollectorUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenAListOfPosts_whenGroupedByTypeAndTheirTitlesAreJoinedInAString_thenGetAMapBetweenTypeAndCsvTitles() {
|
void givenAListOfPosts_whenGroupedByTypeAndTheirTitlesAreJoinedInAString_thenGetAMapBetweenTypeAndCsvTitles() {
|
||||||
Map<BlogPostType, String> postsPerType = posts.stream()
|
Map<BlogPostType, String> postsPerType = posts.stream()
|
||||||
.collect(groupingBy(BlogPost::getType, mapping(BlogPost::getTitle, joining(", ", "Post titles: [", "]"))));
|
.collect(groupingBy(BlogPost::getType, mapping(BlogPost::getTitle, joining(", ", "Post titles: [", "]"))));
|
||||||
|
|
||||||
@ -62,7 +62,7 @@ public class JavaGroupingByCollectorUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenAListOfPosts_whenGroupedByTypeAndSumTheLikes_thenGetAMapBetweenTypeAndPostLikes() {
|
void givenAListOfPosts_whenGroupedByTypeAndSumTheLikes_thenGetAMapBetweenTypeAndPostLikes() {
|
||||||
Map<BlogPostType, Integer> likesPerType = posts.stream()
|
Map<BlogPostType, Integer> likesPerType = posts.stream()
|
||||||
.collect(groupingBy(BlogPost::getType, summingInt(BlogPost::getLikes)));
|
.collect(groupingBy(BlogPost::getType, summingInt(BlogPost::getLikes)));
|
||||||
|
|
||||||
@ -75,7 +75,7 @@ public class JavaGroupingByCollectorUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenAListOfPosts_whenGroupedByTypeInAnEnumMap_thenGetAnEnumMapBetweenTypeAndPosts() {
|
void givenAListOfPosts_whenGroupedByTypeInAnEnumMap_thenGetAnEnumMapBetweenTypeAndPosts() {
|
||||||
EnumMap<BlogPostType, List<BlogPost>> postsPerType = posts.stream()
|
EnumMap<BlogPostType, List<BlogPost>> postsPerType = posts.stream()
|
||||||
.collect(groupingBy(BlogPost::getType, () -> new EnumMap<>(BlogPostType.class), toList()));
|
.collect(groupingBy(BlogPost::getType, () -> new EnumMap<>(BlogPostType.class), toList()));
|
||||||
|
|
||||||
@ -88,7 +88,7 @@ public class JavaGroupingByCollectorUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenAListOfPosts_whenGroupedByTypeInSets_thenGetAMapBetweenTypesAndSetsOfPosts() {
|
void givenAListOfPosts_whenGroupedByTypeInSets_thenGetAMapBetweenTypesAndSetsOfPosts() {
|
||||||
Map<BlogPostType, Set<BlogPost>> postsPerType = posts.stream()
|
Map<BlogPostType, Set<BlogPost>> postsPerType = posts.stream()
|
||||||
.collect(groupingBy(BlogPost::getType, toSet()));
|
.collect(groupingBy(BlogPost::getType, toSet()));
|
||||||
|
|
||||||
@ -101,7 +101,7 @@ public class JavaGroupingByCollectorUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenAListOfPosts_whenGroupedByTypeConcurrently_thenGetAMapBetweenTypeAndPosts() {
|
void givenAListOfPosts_whenGroupedByTypeConcurrently_thenGetAMapBetweenTypeAndPosts() {
|
||||||
ConcurrentMap<BlogPostType, List<BlogPost>> postsPerType = posts.parallelStream()
|
ConcurrentMap<BlogPostType, List<BlogPost>> postsPerType = posts.parallelStream()
|
||||||
.collect(groupingByConcurrent(BlogPost::getType));
|
.collect(groupingByConcurrent(BlogPost::getType));
|
||||||
|
|
||||||
@ -114,7 +114,7 @@ public class JavaGroupingByCollectorUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenAListOfPosts_whenGroupedByTypeAndAveragingLikes_thenGetAMapBetweenTypeAndAverageNumberOfLikes() {
|
void givenAListOfPosts_whenGroupedByTypeAndAveragingLikes_thenGetAMapBetweenTypeAndAverageNumberOfLikes() {
|
||||||
Map<BlogPostType, Double> averageLikesPerType = posts.stream()
|
Map<BlogPostType, Double> averageLikesPerType = posts.stream()
|
||||||
.collect(groupingBy(BlogPost::getType, averagingInt(BlogPost::getLikes)));
|
.collect(groupingBy(BlogPost::getType, averagingInt(BlogPost::getLikes)));
|
||||||
|
|
||||||
@ -127,7 +127,7 @@ public class JavaGroupingByCollectorUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenAListOfPosts_whenGroupedByTypeAndCounted_thenGetAMapBetweenTypeAndNumberOfPosts() {
|
void givenAListOfPosts_whenGroupedByTypeAndCounted_thenGetAMapBetweenTypeAndNumberOfPosts() {
|
||||||
Map<BlogPostType, Long> numberOfPostsPerType = posts.stream()
|
Map<BlogPostType, Long> numberOfPostsPerType = posts.stream()
|
||||||
.collect(groupingBy(BlogPost::getType, counting()));
|
.collect(groupingBy(BlogPost::getType, counting()));
|
||||||
|
|
||||||
@ -140,7 +140,7 @@ public class JavaGroupingByCollectorUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenAListOfPosts_whenGroupedByTypeAndMaxingLikes_thenGetAMapBetweenTypeAndMaximumNumberOfLikes() {
|
void givenAListOfPosts_whenGroupedByTypeAndMaxingLikes_thenGetAMapBetweenTypeAndMaximumNumberOfLikes() {
|
||||||
Map<BlogPostType, Optional<BlogPost>> maxLikesPerPostType = posts.stream()
|
Map<BlogPostType, Optional<BlogPost>> maxLikesPerPostType = posts.stream()
|
||||||
.collect(groupingBy(BlogPost::getType, maxBy(comparingInt(BlogPost::getLikes))));
|
.collect(groupingBy(BlogPost::getType, maxBy(comparingInt(BlogPost::getLikes))));
|
||||||
|
|
||||||
@ -164,7 +164,7 @@ public class JavaGroupingByCollectorUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenAListOfPosts_whenGroupedByAuthorAndThenByType_thenGetAMapBetweenAuthorAndMapsBetweenTypeAndBlogPosts() {
|
void givenAListOfPosts_whenGroupedByAuthorAndThenByType_thenGetAMapBetweenAuthorAndMapsBetweenTypeAndBlogPosts() {
|
||||||
Map<String, Map<BlogPostType, List<BlogPost>>> map = posts.stream()
|
Map<String, Map<BlogPostType, List<BlogPost>>> map = posts.stream()
|
||||||
.collect(groupingBy(BlogPost::getAuthor, groupingBy(BlogPost::getType)));
|
.collect(groupingBy(BlogPost::getAuthor, groupingBy(BlogPost::getType)));
|
||||||
|
|
||||||
@ -189,7 +189,7 @@ public class JavaGroupingByCollectorUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenAListOfPosts_whenGroupedByTypeAndSummarizingLikes_thenGetAMapBetweenTypeAndSummary() {
|
void givenAListOfPosts_whenGroupedByTypeAndSummarizingLikes_thenGetAMapBetweenTypeAndSummary() {
|
||||||
Map<BlogPostType, IntSummaryStatistics> likeStatisticsPerType = posts.stream()
|
Map<BlogPostType, IntSummaryStatistics> likeStatisticsPerType = posts.stream()
|
||||||
.collect(groupingBy(BlogPost::getType, summarizingInt(BlogPost::getLikes)));
|
.collect(groupingBy(BlogPost::getType, summarizingInt(BlogPost::getLikes)));
|
||||||
|
|
||||||
@ -203,7 +203,7 @@ public class JavaGroupingByCollectorUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenAListOfPosts_whenGroupedByComplexMapPairKeyType_thenGetAMapBetweenPairAndList() {
|
void givenAListOfPosts_whenGroupedByComplexMapPairKeyType_thenGetAMapBetweenPairAndList() {
|
||||||
|
|
||||||
Map<Pair<BlogPostType, String>, List<BlogPost>> postsPerTypeAndAuthor = posts.stream()
|
Map<Pair<BlogPostType, String>, List<BlogPost>> postsPerTypeAndAuthor = posts.stream()
|
||||||
.collect(groupingBy(post -> new ImmutablePair<>(post.getType(), post.getAuthor())));
|
.collect(groupingBy(post -> new ImmutablePair<>(post.getType(), post.getAuthor())));
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.streams;
|
package com.baeldung.streams.map;
|
||||||
|
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
@ -1,79 +1,80 @@
|
|||||||
package com.baeldung.reduce;
|
package com.baeldung.streams.reduce;
|
||||||
|
|
||||||
import com.baeldung.reduce.entities.User;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
import com.baeldung.reduce.utilities.NumberUtils;
|
|
||||||
import org.junit.Test;
|
import com.baeldung.streams.reduce.entities.User;
|
||||||
|
import com.baeldung.streams.reduce.utilities.NumberUtils;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
class StreamReduceUnitTest {
|
||||||
|
|
||||||
public class StreamReduceUnitTest {
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenIntegerList_whenReduceWithSumAccumulatorLambda_thenCorrect() {
|
void givenIntegerList_whenReduceWithSumAccumulatorLambda_thenCorrect() {
|
||||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||||
int result = numbers.stream().reduce(0, (subtotal, element) -> subtotal + element);
|
int result = numbers.stream().reduce(0, (subtotal, element) -> subtotal + element);
|
||||||
assertThat(result).isEqualTo(21);
|
assertThat(result).isEqualTo(21);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenIntegerList_whenReduceWithSumAccumulatorMethodReference_thenCorrect() {
|
void givenIntegerList_whenReduceWithSumAccumulatorMethodReference_thenCorrect() {
|
||||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||||
int result = numbers.stream().reduce(0, Integer::sum);
|
int result = numbers.stream().reduce(0, Integer::sum);
|
||||||
assertThat(result).isEqualTo(21);
|
assertThat(result).isEqualTo(21);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenStringList_whenReduceWithConcatenatorAccumulatorLambda_thenCorrect() {
|
void givenStringList_whenReduceWithConcatenatorAccumulatorLambda_thenCorrect() {
|
||||||
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
||||||
String result = letters.stream().reduce("", (partialString, element) -> partialString + element);
|
String result = letters.stream().reduce("", (partialString, element) -> partialString + element);
|
||||||
assertThat(result).isEqualTo("abcde");
|
assertThat(result).isEqualTo("abcde");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenStringList_whenReduceWithConcatenatorAccumulatorMethodReference_thenCorrect() {
|
void givenStringList_whenReduceWithConcatenatorAccumulatorMethodReference_thenCorrect() {
|
||||||
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
||||||
String result = letters.stream().reduce("", String::concat);
|
String result = letters.stream().reduce("", String::concat);
|
||||||
assertThat(result).isEqualTo("abcde");
|
assertThat(result).isEqualTo("abcde");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenStringList_whenReduceWithUppercaseConcatenatorAccumulator_thenCorrect() {
|
void givenStringList_whenReduceWithUppercaseConcatenatorAccumulator_thenCorrect() {
|
||||||
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
||||||
String result = letters.stream().reduce("", (partialString, element) -> partialString.toUpperCase() + element.toUpperCase());
|
String result = letters.stream().reduce("", (partialString, element) -> partialString.toUpperCase() + element.toUpperCase());
|
||||||
assertThat(result).isEqualTo("ABCDE");
|
assertThat(result).isEqualTo("ABCDE");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenUserList_whenReduceWithAgeAccumulatorAndSumCombiner_thenCorrect() {
|
void givenUserList_whenReduceWithAgeAccumulatorAndSumCombiner_thenCorrect() {
|
||||||
List<User> users = Arrays.asList(new User("John", 30), new User("Julie", 35));
|
List<User> users = Arrays.asList(new User("John", 30), new User("Julie", 35));
|
||||||
int result = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
|
int result = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
|
||||||
assertThat(result).isEqualTo(65);
|
assertThat(result).isEqualTo(65);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenStringList_whenReduceWithParallelStream_thenCorrect() {
|
void givenStringList_whenReduceWithParallelStream_thenCorrect() {
|
||||||
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
||||||
String result = letters.parallelStream().reduce("", String::concat);
|
String result = letters.parallelStream().reduce("", String::concat);
|
||||||
assertThat(result).isEqualTo("abcde");
|
assertThat(result).isEqualTo("abcde");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenNumberUtilsClass_whenCalledDivideListElements_thenCorrect() {
|
void givenNumberUtilsClass_whenCalledDivideListElements_thenCorrect() {
|
||||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||||
assertThat(NumberUtils.divideListElements(numbers, 1)).isEqualTo(21);
|
assertThat(NumberUtils.divideListElements(numbers, 1)).isEqualTo(21);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenNumberUtilsClass_whenCalledDivideListElementsWithExtractedTryCatchBlock_thenCorrect() {
|
void givenNumberUtilsClass_whenCalledDivideListElementsWithExtractedTryCatchBlock_thenCorrect() {
|
||||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||||
assertThat(NumberUtils.divideListElementsWithExtractedTryCatchBlock(numbers, 1)).isEqualTo(21);
|
assertThat(NumberUtils.divideListElementsWithExtractedTryCatchBlock(numbers, 1)).isEqualTo(21);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenStream_whneCalleddivideListElementsWithApplyFunctionMethod_thenCorrect() {
|
void givenStream_whneCalleddivideListElementsWithApplyFunctionMethod_thenCorrect() {
|
||||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||||
assertThat(NumberUtils.divideListElementsWithApplyFunctionMethod(numbers, 1)).isEqualTo(21);
|
assertThat(NumberUtils.divideListElementsWithApplyFunctionMethod(numbers, 1)).isEqualTo(21);
|
||||||
}
|
}
|
@ -9,7 +9,6 @@ This module contains articles about the Stream API in Java.
|
|||||||
- [Iterable to Stream in Java](https://www.baeldung.com/java-iterable-to-stream)
|
- [Iterable to Stream in Java](https://www.baeldung.com/java-iterable-to-stream)
|
||||||
- [How to Iterate Over a Stream With Indices](https://www.baeldung.com/java-stream-indices)
|
- [How to Iterate Over a Stream With Indices](https://www.baeldung.com/java-stream-indices)
|
||||||
- [Stream Ordering in Java](https://www.baeldung.com/java-stream-ordering)
|
- [Stream Ordering in Java](https://www.baeldung.com/java-stream-ordering)
|
||||||
- [Java Stream Filter with Lambda Expression](https://www.baeldung.com/java-stream-filter-lambda)
|
|
||||||
- [Counting Matches on a Stream Filter](https://www.baeldung.com/java-stream-filter-count)
|
- [Counting Matches on a Stream Filter](https://www.baeldung.com/java-stream-filter-count)
|
||||||
- [Summing Numbers with Java Streams](https://www.baeldung.com/java-stream-sum)
|
- [Summing Numbers with Java Streams](https://www.baeldung.com/java-stream-sum)
|
||||||
- [How to Find All Getters Returning Null](https://www.baeldung.com/java-getters-returning-null)
|
- [How to Find All Getters Returning Null](https://www.baeldung.com/java-getters-returning-null)
|
||||||
|
@ -29,11 +29,6 @@
|
|||||||
<artifactId>streamex</artifactId>
|
<artifactId>streamex</artifactId>
|
||||||
<version>${streamex.version}</version>
|
<version>${streamex.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
|
||||||
<groupId>com.pivovarit</groupId>
|
|
||||||
<artifactId>throwing-function</artifactId>
|
|
||||||
<version>${throwing-function.version}</version>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
@ -62,8 +57,6 @@
|
|||||||
<vavr.version>0.10.4</vavr.version>
|
<vavr.version>0.10.4</vavr.version>
|
||||||
<protonpack.version>1.16</protonpack.version>
|
<protonpack.version>1.16</protonpack.version>
|
||||||
<streamex.version>0.8.1</streamex.version>
|
<streamex.version>0.8.1</streamex.version>
|
||||||
<throwing-function.version>1.5.1</throwing-function.version>
|
|
||||||
|
|
||||||
<maven.compiler.source>17</maven.compiler.source>
|
<maven.compiler.source>17</maven.compiler.source>
|
||||||
<maven.compiler.target>17</maven.compiler.target>
|
<maven.compiler.target>17</maven.compiler.target>
|
||||||
</properties>
|
</properties>
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user