Merge branch 'eugenp:master' into PR-7308
This commit is contained in:
@@ -45,7 +45,7 @@
|
||||
<properties>
|
||||
<maven.compiler.source.version>11</maven.compiler.source.version>
|
||||
<maven.compiler.target.version>11</maven.compiler.target.version>
|
||||
<jackson.version>2.14.1</jackson.version>
|
||||
<jackson.version>2.16.0</jackson.version>
|
||||
<gson.version>2.10</gson.version>
|
||||
</properties>
|
||||
|
||||
|
||||
@@ -21,8 +21,4 @@
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<java.version>17</java.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -13,8 +13,4 @@
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<java.version>17</java.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -26,8 +26,4 @@
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<java.version>17</java.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -3,19 +3,34 @@
|
||||
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-20</artifactId>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>core-java-20</artifactId>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>20</maven.compiler.source>
|
||||
<maven.compiler.target>20</maven.compiler.target>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>jakarta.servlet</groupId>
|
||||
<artifactId>jakarta.servlet-api</artifactId>
|
||||
<version>6.0.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>3.24.2</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-junit-jupiter</artifactId>
|
||||
<version>5.2.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
@@ -41,25 +56,10 @@
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>jakarta.servlet</groupId>
|
||||
<artifactId>jakarta.servlet-api</artifactId>
|
||||
<version>6.0.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>3.24.2</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-junit-jupiter</artifactId>
|
||||
<version>5.2.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<properties>
|
||||
<maven.compiler.source>20</maven.compiler.source>
|
||||
<maven.compiler.target>20</maven.compiler.target>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -11,3 +11,4 @@ This module contains articles about arrays conversion in Java
|
||||
- [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 Char Array to Int Array in Java](https://www.baeldung.com/java-convert-char-int-array)
|
||||
- [How to Convert Byte Array to Char Array](https://www.baeldung.com/java-convert-byte-array-char)
|
||||
|
||||
@@ -57,7 +57,7 @@
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
<properties>
|
||||
<maven.compiler.release>11</maven.compiler.release>
|
||||
</properties>
|
||||
|
||||
@@ -43,7 +43,6 @@
|
||||
|
||||
<properties>
|
||||
<vavr.version>0.10.3</vavr.version>
|
||||
<java.version>11</java.version>
|
||||
<modelmapper.version>3.2.0</modelmapper.version>
|
||||
</properties>
|
||||
</project>
|
||||
@@ -39,7 +39,7 @@
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>1.18.26</version>
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@@ -67,7 +67,7 @@
|
||||
<jmh.version>1.21</jmh.version>
|
||||
<commons-lang.version>2.2</commons-lang.version>
|
||||
<gson.version>2.10.1</gson.version>
|
||||
<jackson.version>2.15.2</jackson.version>
|
||||
<jackson.version>2.16.0</jackson.version>
|
||||
<org.json.version>20230618</org.json.version>
|
||||
</properties>
|
||||
</project>
|
||||
@@ -13,14 +13,11 @@
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<spring.version>5.2.5.RELEASE</spring.version>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>2.13.1</version>
|
||||
<version>2.16.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
@@ -51,4 +48,8 @@
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<spring.version>5.2.5.RELEASE</spring.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -4,5 +4,7 @@
|
||||
- [How to Write Hashmap to CSV File](https://www.baeldung.com/java-write-hashmap-csv)
|
||||
- [How to Get First or Last Entry From a LinkedHashMap in Java](https://www.baeldung.com/java-linkedhashmap-first-last-key-value-pair)
|
||||
- [How to Write and Read a File with a Java HashMap](https://www.baeldung.com/java-hashmap-write-read-file)
|
||||
- [Limiting the Max Size of a HashMap in Java](https://www.baeldung.com/java-hashmap-max-size)
|
||||
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-6)
|
||||
- [Limiting the Max Size of a HashMap in Java](https://www.baeldung.com/java-hashmap-size-bound)
|
||||
- [How to Sort LinkedHashMap By Values in Java](https://www.baeldung.com/java-sort-linkedhashmap-using-values)
|
||||
- [How to Increment a Map Value in Java](https://www.baeldung.com/java-increment-map-value)
|
||||
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-6)
|
||||
|
||||
@@ -1,15 +1,11 @@
|
||||
<?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">
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-collections-maps-7</artifactId>
|
||||
<name>core-java-collections-maps-7</name>
|
||||
<packaging>jar</packaging>
|
||||
<properties>
|
||||
<gson.version>2.10.1</gson.version>
|
||||
<csv.version>1.5</csv.version>
|
||||
</properties>
|
||||
|
||||
<parent>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
@@ -63,4 +59,10 @@
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<gson.version>2.10.1</gson.version>
|
||||
<csv.version>1.5</csv.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
+150
@@ -0,0 +1,150 @@
|
||||
package com.baeldung.concurrent.completablefuture;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class CompletableFutureUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenAsyncTask_whenProcessingAsyncSucceed_thenReturnSuccess() throws ExecutionException, InterruptedException {
|
||||
Microservice mockMicroserviceA = mock(Microservice.class);
|
||||
Microservice mockMicroserviceB = mock(Microservice.class);
|
||||
|
||||
when(mockMicroserviceA.retrieveAsync(any())).thenReturn(CompletableFuture.completedFuture("Hello"));
|
||||
when(mockMicroserviceB.retrieveAsync(any())).thenReturn(CompletableFuture.completedFuture("World"));
|
||||
|
||||
CompletableFuture<String> resultFuture = processAsync(List.of(mockMicroserviceA, mockMicroserviceB));
|
||||
|
||||
String result = resultFuture.get();
|
||||
assertEquals("HelloWorld", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAsyncTask_whenProcessingAsyncWithException_thenReturnException() throws ExecutionException, InterruptedException {
|
||||
Microservice mockMicroserviceA = mock(Microservice.class);
|
||||
Microservice mockMicroserviceB = mock(Microservice.class);
|
||||
|
||||
when(mockMicroserviceA.retrieveAsync(any())).thenReturn(CompletableFuture.completedFuture("Hello"));
|
||||
when(mockMicroserviceB.retrieveAsync(any())).thenReturn(CompletableFuture.failedFuture(new RuntimeException("Simulated Exception")));
|
||||
CompletableFuture<String> resultFuture = processAsync(List.of(mockMicroserviceA, mockMicroserviceB));
|
||||
// Use assertThrows to verify that the expected exception is thrown
|
||||
ExecutionException exception = assertThrows(ExecutionException.class, resultFuture::get);
|
||||
// Assert the exception message
|
||||
assertEquals("Simulated Exception", exception.getCause()
|
||||
.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAsyncTask_whenProcessingAsyncWithTimeout_thenHandleTimeoutException() throws ExecutionException, InterruptedException {
|
||||
Microservice mockMicroserviceA = mock(Microservice.class);
|
||||
Microservice mockMicroserviceB = mock(Microservice.class);
|
||||
Executor delayedExecutor = CompletableFuture.delayedExecutor(200, TimeUnit.MILLISECONDS);
|
||||
when(mockMicroserviceA.retrieveAsync(any())).thenReturn(CompletableFuture.supplyAsync(() -> "Hello", delayedExecutor));
|
||||
Executor delayedExecutor2 = CompletableFuture.delayedExecutor(500, TimeUnit.MILLISECONDS);
|
||||
when(mockMicroserviceB.retrieveAsync(any())).thenReturn(CompletableFuture.supplyAsync(() -> "World", delayedExecutor2));
|
||||
CompletableFuture<String> resultFuture = processAsync(List.of(mockMicroserviceA, mockMicroserviceB));
|
||||
assertThrows(TimeoutException.class, () -> resultFuture.get(300, TimeUnit.MILLISECONDS));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCompletableFuture_whenCompleted_thenStateIsDone() {
|
||||
Executor delayedExecutor = CompletableFuture.delayedExecutor(200, TimeUnit.MILLISECONDS);
|
||||
CompletableFuture<String> cf1 = CompletableFuture.supplyAsync(() -> "Hello", delayedExecutor);
|
||||
CompletableFuture<String> cf2 = CompletableFuture.supplyAsync(() -> " World");
|
||||
CompletableFuture<String> cf3 = CompletableFuture.supplyAsync(() -> "!");
|
||||
CompletableFuture<String>[] cfs = new CompletableFuture[] { cf1, cf2, cf3 };
|
||||
|
||||
CompletableFuture<Void> allCf = CompletableFuture.allOf(cfs);
|
||||
|
||||
assertFalse(allCf.isDone());
|
||||
allCf.join();
|
||||
String result = Arrays.stream(cfs)
|
||||
.map(CompletableFuture::join)
|
||||
.collect(Collectors.joining());
|
||||
|
||||
assertFalse(allCf.isCancelled());
|
||||
assertTrue(allCf.isDone());
|
||||
assertFalse(allCf.isCompletedExceptionally());
|
||||
assertEquals(result, "Hello World!");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCompletableFuture_whenCompletedWithException_thenStateIsCompletedExceptionally() throws ExecutionException, InterruptedException {
|
||||
Executor delayedExecutor = CompletableFuture.delayedExecutor(200, TimeUnit.MILLISECONDS);
|
||||
CompletableFuture<String> cf1 = CompletableFuture.supplyAsync(() -> "Hello", delayedExecutor);
|
||||
CompletableFuture<String> cf2 = CompletableFuture.failedFuture(new RuntimeException("Simulated Exception"));
|
||||
CompletableFuture<String> cf3 = CompletableFuture.supplyAsync(() -> "!");
|
||||
CompletableFuture<String>[] cfs = new CompletableFuture[] { cf1, cf2, cf3 };
|
||||
|
||||
CompletableFuture<Void> allCf = CompletableFuture.allOf(cfs);
|
||||
|
||||
assertFalse(allCf.isDone());
|
||||
assertFalse(allCf.isCompletedExceptionally());
|
||||
|
||||
// Exception is expected, assert the cause
|
||||
CompletionException exception = assertThrows(CompletionException.class, allCf::join);
|
||||
|
||||
assertEquals("Simulated Exception", exception.getCause()
|
||||
.getMessage());
|
||||
assertTrue(allCf.isCompletedExceptionally());
|
||||
assertTrue(allCf.isDone());
|
||||
assertFalse(allCf.isCancelled());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCompletableFuture_whenCancelled_thenStateIsCancelled() throws ExecutionException, InterruptedException {
|
||||
Executor delayedExecutor = CompletableFuture.delayedExecutor(200, TimeUnit.MILLISECONDS);
|
||||
CompletableFuture<String> cf1 = CompletableFuture.supplyAsync(() -> "Hello", delayedExecutor);
|
||||
CompletableFuture<String> cf2 = CompletableFuture.supplyAsync(() -> " World");
|
||||
CompletableFuture<String> cf3 = CompletableFuture.supplyAsync(() -> "!");
|
||||
CompletableFuture<String>[] cfs = new CompletableFuture[] { cf1, cf2, cf3 };
|
||||
CompletableFuture<Void> allCf = CompletableFuture.allOf(cfs);
|
||||
assertFalse(allCf.isDone());
|
||||
assertFalse(allCf.isCompletedExceptionally());
|
||||
allCf.cancel(true);
|
||||
assertTrue(allCf.isCancelled());
|
||||
assertTrue(allCf.isDone());
|
||||
}
|
||||
|
||||
CompletableFuture<String> processAsync(List<Microservice> microservices) {
|
||||
List<CompletableFuture<String>> dataFetchFutures = fetchDataAsync(microservices);
|
||||
return combineResults(dataFetchFutures);
|
||||
}
|
||||
|
||||
private List<CompletableFuture<String>> fetchDataAsync(List<Microservice> microservices) {
|
||||
return microservices.stream()
|
||||
.map(client -> client.retrieveAsync(""))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private CompletableFuture<String> combineResults(List<CompletableFuture<String>> dataFetchFutures) {
|
||||
return CompletableFuture.allOf(dataFetchFutures.toArray(new CompletableFuture[0]))
|
||||
.thenApply(v -> dataFetchFutures.stream()
|
||||
.map(future -> future.exceptionally(ex -> {
|
||||
throw new CompletionException(ex);
|
||||
})
|
||||
.join())
|
||||
.collect(Collectors.joining()));
|
||||
}
|
||||
|
||||
interface Microservice {
|
||||
CompletableFuture<String> retrieveAsync(String input);
|
||||
}
|
||||
}
|
||||
@@ -11,3 +11,4 @@ This module contains articles about converting between Java date and time object
|
||||
- [Conversion From 12-Hour Time to 24-Hour Time in Java](https://www.baeldung.com/java-convert-time-format)
|
||||
- [Convert Epoch Time to LocalDate and LocalDateTime](https://www.baeldung.com/java-convert-epoch-localdate)
|
||||
- [Convert Timestamp String to Long in Java](https://www.baeldung.com/java-convert-timestamp-string-long)
|
||||
- [Convert Long Timestamp to LocalDateTime in Java](https://www.baeldung.com/java-convert-long-timestamp-localdatetime)
|
||||
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.lazylambda;
|
||||
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public class LambdaSupplier<T> {
|
||||
|
||||
protected final Supplier<T> expensiveData;
|
||||
|
||||
public LambdaSupplier(Supplier<T> expensiveData) {
|
||||
this.expensiveData = expensiveData;
|
||||
}
|
||||
|
||||
public T getData() {
|
||||
return expensiveData.get();
|
||||
}
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.lazylambda;
|
||||
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public class LazyLambdaSupplier<T> extends LambdaSupplier<T> {
|
||||
|
||||
private T data;
|
||||
|
||||
public LazyLambdaSupplier(Supplier<T> expensiveData) {
|
||||
super(expensiveData);
|
||||
}
|
||||
|
||||
@Override
|
||||
public T getData() {
|
||||
if (data != null) {
|
||||
return data;
|
||||
}
|
||||
return data = expensiveData.get();
|
||||
}
|
||||
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.lazylambda;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public class LazyLambdaThreadSafeSupplier<T> extends LambdaSupplier<T> {
|
||||
|
||||
private final AtomicReference<T> data;
|
||||
|
||||
public LazyLambdaThreadSafeSupplier(Supplier<T> expensiveData) {
|
||||
super(expensiveData);
|
||||
data = new AtomicReference<>();
|
||||
}
|
||||
|
||||
public T getData() {
|
||||
if (data.get() == null) {
|
||||
synchronized (data) {
|
||||
if (data.get() == null) {
|
||||
data.set(expensiveData.get());
|
||||
}
|
||||
}
|
||||
}
|
||||
return data.get();
|
||||
}
|
||||
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.lazylambda;
|
||||
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
public class LambdaSupplierUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenCalledMultipleTimes_thenShouldBeCalledMultipleTimes() {
|
||||
@SuppressWarnings("unchecked") Supplier<String> mockedExpensiveFunction = Mockito.mock(Supplier.class);
|
||||
Mockito.when(mockedExpensiveFunction.get())
|
||||
.thenReturn("expensive call");
|
||||
LambdaSupplier<String> testee = new LambdaSupplier<>(mockedExpensiveFunction);
|
||||
Mockito.verify(mockedExpensiveFunction, Mockito.never())
|
||||
.get();
|
||||
testee.getData();
|
||||
testee.getData();
|
||||
Mockito.verify(mockedExpensiveFunction, Mockito.times(2))
|
||||
.get();
|
||||
}
|
||||
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package com.baeldung.lazylambda;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.stubbing.Answer;
|
||||
|
||||
public class LazyLambdaSupplierUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenCalledMultipleTimes_thenShouldBeCalledOnlyOnce() {
|
||||
@SuppressWarnings("unchecked") Supplier<String> mockedExpensiveFunction = Mockito.mock(Supplier.class);
|
||||
Mockito.when(mockedExpensiveFunction.get())
|
||||
.thenReturn("expensive call");
|
||||
LazyLambdaSupplier<String> testee = new LazyLambdaSupplier<>(mockedExpensiveFunction);
|
||||
Mockito.verify(mockedExpensiveFunction, Mockito.never())
|
||||
.get();
|
||||
testee.getData();
|
||||
testee.getData();
|
||||
Mockito.verify(mockedExpensiveFunction, Mockito.times(1))
|
||||
.get();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCalledMultipleTimesConcurrently_thenShouldBeCalledMultipleTimes() throws InterruptedException {
|
||||
@SuppressWarnings("unchecked") Supplier<String> mockedExpensiveFunction = Mockito.mock(Supplier.class);
|
||||
Mockito.when(mockedExpensiveFunction.get())
|
||||
.thenAnswer((Answer<String>) invocation -> {
|
||||
Thread.sleep(1000L);
|
||||
return "Late response!";
|
||||
});
|
||||
LazyLambdaSupplier<String> testee = new LazyLambdaSupplier<>(mockedExpensiveFunction);
|
||||
Mockito.verify(mockedExpensiveFunction, Mockito.never())
|
||||
.get();
|
||||
|
||||
ExecutorService executorService = Executors.newFixedThreadPool(4);
|
||||
executorService.invokeAll(List.of(testee::getData, testee::getData));
|
||||
executorService.shutdown();
|
||||
if (!executorService.awaitTermination(5, TimeUnit.SECONDS)) {
|
||||
executorService.shutdownNow();
|
||||
}
|
||||
|
||||
Mockito.verify(mockedExpensiveFunction, Mockito.times(2))
|
||||
.get();
|
||||
}
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package com.baeldung.lazylambda;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.stubbing.Answer;
|
||||
|
||||
public class LazyLambdaThreadSafeSupplierUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenCalledMultipleTimes_thenShouldBeCalledOnlyOnce() {
|
||||
@SuppressWarnings("unchecked") Supplier<String> mockedExpensiveFunction = Mockito.mock(Supplier.class);
|
||||
Mockito.when(mockedExpensiveFunction.get())
|
||||
.thenReturn("expensive call");
|
||||
LazyLambdaThreadSafeSupplier<String> testee = new LazyLambdaThreadSafeSupplier<>(mockedExpensiveFunction);
|
||||
Mockito.verify(mockedExpensiveFunction, Mockito.never())
|
||||
.get();
|
||||
testee.getData();
|
||||
testee.getData();
|
||||
Mockito.verify(mockedExpensiveFunction, Mockito.times(1))
|
||||
.get();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCalledMultipleTimesConcurrently_thenShouldBeCalledOnlyOnce() throws InterruptedException {
|
||||
@SuppressWarnings("unchecked") Supplier<String> mockedExpensiveFunction = Mockito.mock(Supplier.class);
|
||||
Mockito.when(mockedExpensiveFunction.get())
|
||||
.thenAnswer((Answer<String>) invocation -> {
|
||||
Thread.sleep(1000L);
|
||||
return "Late response!";
|
||||
});
|
||||
LazyLambdaThreadSafeSupplier<String> testee = new LazyLambdaThreadSafeSupplier<>(mockedExpensiveFunction);
|
||||
Mockito.verify(mockedExpensiveFunction, Mockito.never())
|
||||
.get();
|
||||
|
||||
ExecutorService executorService = Executors.newFixedThreadPool(4);
|
||||
executorService.invokeAll(List.of(testee::getData, testee::getData));
|
||||
executorService.shutdown();
|
||||
if (!executorService.awaitTermination(5, TimeUnit.SECONDS)) {
|
||||
executorService.shutdownNow();
|
||||
}
|
||||
|
||||
Mockito.verify(mockedExpensiveFunction, Mockito.times(1))
|
||||
.get();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -9,3 +9,5 @@ This module contains articles about core features in the Java language
|
||||
- [Get a Random Element From a Set in Java](https://www.baeldung.com/java-set-draw-sample)
|
||||
- [Stop Executing Further Code in Java](https://www.baeldung.com/java-stop-running-code)
|
||||
- [Using the Apache Commons Lang 3 for Comparing Objects in Java](https://www.baeldung.com/java-apache-commons-lang-3-compare-objects)
|
||||
- [Return First Non-null Value in Java](https://www.baeldung.com/java-first-non-null)
|
||||
- [Static Final Variables in Java](https://www.baeldung.com/java-static-final-variables)
|
||||
|
||||
@@ -23,6 +23,16 @@
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>${jmh.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${jmh.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<plugins>
|
||||
@@ -39,6 +49,11 @@
|
||||
<artifactId>mapstruct-processor</artifactId>
|
||||
<version>${mapstruct.version}</version>
|
||||
</path>
|
||||
<path>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${jmh.version}</version>
|
||||
</path>
|
||||
</annotationProcessorPaths>
|
||||
</configuration>
|
||||
</plugin>
|
||||
@@ -50,6 +65,7 @@
|
||||
<maven.compiler.target>17</maven.compiler.target>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<mapstruct.version>1.6.0.Beta1</mapstruct.version>
|
||||
<jmh.version>1.37</jmh.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.staticfinal;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
public class Bike {
|
||||
public static final int TIRE = 2;
|
||||
public static final int PEDAL;
|
||||
public static final HashMap<String, Integer> PART = new HashMap<>();
|
||||
|
||||
static {
|
||||
PEDAL = 5;
|
||||
}
|
||||
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.recursivelysumintarray;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class RecursivelySumIntArrayUnitTest {
|
||||
|
||||
private static final int[] INT_ARRAY = { 1, 2, 3, 4, 5 };
|
||||
|
||||
static int sumIntArray1(int[] array) {
|
||||
if (array.length == 1) {
|
||||
return array[0];
|
||||
} else {
|
||||
return array[0] + sumIntArray1(Arrays.copyOfRange(array, 1, array.length));
|
||||
}
|
||||
}
|
||||
|
||||
static int sumIntArray2(int[] array, int index) {
|
||||
if (index == 0) {
|
||||
return array[index];
|
||||
} else {
|
||||
return array[index] + sumIntArray2(array, index - 1);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingSumIntArray1_thenGetExpectedResult() {
|
||||
assertEquals(15, sumIntArray1(INT_ARRAY));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingSumIntArray2_thenGetExpectedResult() {
|
||||
assertEquals(15, sumIntArray2(INT_ARRAY, INT_ARRAY.length - 1));
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
package com.baeldung.recursivelysumintarray;
|
||||
|
||||
import static com.baeldung.recursivelysumintarray.RecursivelySumIntArrayUnitTest.sumIntArray1;
|
||||
import static com.baeldung.recursivelysumintarray.RecursivelySumIntArrayUnitTest.sumIntArray2;
|
||||
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.openjdk.jmh.annotations.Benchmark;
|
||||
import org.openjdk.jmh.annotations.BenchmarkMode;
|
||||
import org.openjdk.jmh.annotations.Fork;
|
||||
import org.openjdk.jmh.annotations.Measurement;
|
||||
import org.openjdk.jmh.annotations.Mode;
|
||||
import org.openjdk.jmh.annotations.OutputTimeUnit;
|
||||
import org.openjdk.jmh.annotations.Param;
|
||||
import org.openjdk.jmh.annotations.Scope;
|
||||
import org.openjdk.jmh.annotations.Setup;
|
||||
import org.openjdk.jmh.annotations.State;
|
||||
import org.openjdk.jmh.annotations.Warmup;
|
||||
import org.openjdk.jmh.runner.Runner;
|
||||
import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@State(Scope.Thread)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
@Warmup(iterations = 2)
|
||||
@Fork(1)
|
||||
@Measurement(iterations = 5)
|
||||
public class SumArrayBenchmark {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Options options = new OptionsBuilder().include(SumArrayBenchmark.class.getSimpleName())
|
||||
.build();
|
||||
new Runner(options).run();
|
||||
}
|
||||
|
||||
@Param({ "10", "10000" })
|
||||
public int size;
|
||||
int[] array;
|
||||
|
||||
@Setup
|
||||
public void setup() {
|
||||
var r = new Random();
|
||||
array = new int[size];
|
||||
|
||||
for (int i = 0; i < size; i++) {
|
||||
array[i] = r.nextInt();
|
||||
}
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public int withArrayCopy() {
|
||||
return sumIntArray1(array);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public int withoutArrayCopy() {
|
||||
return sumIntArray2(array, array.length - 1);
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package com.baeldung.staticfinal;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class BikeUnitTest {
|
||||
|
||||
@Test
|
||||
void givenTireConstantSetUponDeclaration_whenGetTire_thenReturnTwo() {
|
||||
assertEquals(2, Bike.TIRE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPedalConstantSetByStaticBlock_whenGetPedal_thenReturnFive() {
|
||||
assertEquals(5, Bike.PEDAL);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPartConstantObject_whenObjectStateChanged_thenCorrect() {
|
||||
Bike.PART.put("seat", 1);
|
||||
assertEquals(1, Bike.PART.get("seat"));
|
||||
|
||||
Bike.PART.put("seat", 5);
|
||||
assertEquals(5, Bike.PART.get("seat"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMathClass_whenAccessingPiConstant_thenVerifyPiValueIsCorrect() {
|
||||
assertEquals(3.141592653589793, Math.PI);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -10,3 +10,4 @@ This module contains articles about Java operators
|
||||
- [Check if at Least Two Out of Three Booleans Are True in Java](https://www.baeldung.com/java-check-two-of-three-booleans)
|
||||
- [Alternatives for instanceof Operator in Java](https://www.baeldung.com/java-instanceof-alternatives)
|
||||
- [What Does “––>” Mean in Java?](https://www.baeldung.com/java-minus-minus-greaterthan)
|
||||
- [All the Ways Java Uses the Colon Character](https://www.baeldung.com/java-colon)
|
||||
|
||||
+178
@@ -0,0 +1,178 @@
|
||||
package com.baeldung.colonexamples;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* Examples of the different ways Java uses the colon (:) character.
|
||||
*/
|
||||
public class ColonExamples {
|
||||
|
||||
private final static Logger LOG = LoggerFactory.getLogger(ColonExamples.class);
|
||||
|
||||
public void example1_enhancedForLoop() {
|
||||
|
||||
// Original style
|
||||
for(int i = 0; i < 10; i++) {
|
||||
// do something
|
||||
}
|
||||
|
||||
// Using enhanced for loop
|
||||
int[] numbers = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9};
|
||||
for(int i : numbers) {
|
||||
// do something
|
||||
}
|
||||
|
||||
// Using List instead of array
|
||||
List<Integer> numbersList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
|
||||
for(Integer i : numbersList) {
|
||||
// do something
|
||||
}
|
||||
}
|
||||
|
||||
public void example2_switchStatement(String animal) {
|
||||
|
||||
// Original style
|
||||
if(animal.equals("cat")) {
|
||||
System.out.println("meow");
|
||||
}
|
||||
else if(animal.equals("lion")) {
|
||||
System.out.println("roar");
|
||||
}
|
||||
else if(animal.equals("dog") || animal.equals("seal")) {
|
||||
System.out.println("bark");
|
||||
}
|
||||
else {
|
||||
System.out.println("unknown");
|
||||
}
|
||||
|
||||
// Using switch statement
|
||||
switch(animal) {
|
||||
case "cat":
|
||||
System.out.println("meow");
|
||||
break;
|
||||
case "lion":
|
||||
System.out.println("roar");
|
||||
break;
|
||||
case "dog":
|
||||
case "seal":
|
||||
System.out.println("bark");
|
||||
break;
|
||||
default:
|
||||
System.out.println("unknown");
|
||||
}
|
||||
}
|
||||
|
||||
public void example3_labels() {
|
||||
|
||||
// For loops without labels
|
||||
for(int i = 0; i < 10; i++) {
|
||||
for (int j = 0; j < 10; j++) {
|
||||
if (checkSomeCondition()) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
outterLoop: for(int i = 0; i < 10; i++) {
|
||||
innerLoop: for (int j = 0; j < 10; j++) {
|
||||
if (checkSomeCondition()) {
|
||||
break outterLoop;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void example4_ternaryOperator() {
|
||||
|
||||
// Original way using if/else
|
||||
int x;
|
||||
if(checkSomeCondition()) {
|
||||
x = 1;
|
||||
}
|
||||
else {
|
||||
x = 2;
|
||||
}
|
||||
|
||||
// Using ternary operator
|
||||
x = checkSomeCondition() ? 1 : 2;
|
||||
|
||||
// Using with other statements
|
||||
boolean remoteCallResult = callRemoteApi();
|
||||
LOG.info(String.format(
|
||||
"The result of the remote API call %s successful",
|
||||
remoteCallResult ? "was" : "was not"
|
||||
));
|
||||
}
|
||||
|
||||
public void example5_methodReferences() {
|
||||
// Original way without lambdas and method references
|
||||
List<String> names = Arrays.asList("ross", "joey", "chandler");
|
||||
List<String> upperCaseNames = new ArrayList<>();
|
||||
for(String name : names) {
|
||||
upperCaseNames.add(name.toUpperCase());
|
||||
}
|
||||
|
||||
// Using method reference with stream map operation
|
||||
List<String> petNames = Arrays.asList("ross", "joey", "chandler");
|
||||
List<String> petUpperCaseNames = petNames
|
||||
.stream()
|
||||
.map(String::toUpperCase)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
// Method reference with stream filter
|
||||
List<Animal> pets = Arrays.asList(new Cat(), new Dog(), new Parrot());
|
||||
List<Animal> onlyDogs = pets
|
||||
.stream()
|
||||
.filter(Dog.class::isInstance)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
// Method reference with constructors
|
||||
Set<Animal> onlyDogsSet = pets
|
||||
.stream()
|
||||
.filter(Dog.class::isInstance)
|
||||
.collect(Collectors.toCollection(TreeSet::new));
|
||||
}
|
||||
|
||||
public void example6_asserttion() {
|
||||
// Original way without assertions
|
||||
Connection conn = getConnection();
|
||||
if(conn == null) {
|
||||
throw new RuntimeException("Connection is null");
|
||||
}
|
||||
|
||||
// Using assert keyword
|
||||
assert getConnection() != null : "Connection is null";
|
||||
}
|
||||
|
||||
private boolean checkSomeCondition() {
|
||||
return new Random().nextBoolean();
|
||||
}
|
||||
|
||||
private boolean callRemoteApi() {
|
||||
return new Random().nextBoolean();
|
||||
}
|
||||
|
||||
private Connection getConnection() {
|
||||
return null;
|
||||
}
|
||||
|
||||
private static interface Animal {
|
||||
|
||||
}
|
||||
private static class Dog implements Animal {
|
||||
|
||||
}
|
||||
|
||||
private static class Cat implements Animal {
|
||||
|
||||
}
|
||||
|
||||
private static class Parrot implements Animal {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
## Relevant Articles
|
||||
- [Check if a double Is an Integer in Java](https://www.baeldung.com/java-check-double-integer)
|
||||
@@ -0,0 +1,37 @@
|
||||
<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-numbers-7</artifactId>
|
||||
<name>core-java-numbers-7</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.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<finalName>core-java-numbers-7</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
</project>
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.bigdecimalzero;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
public class BigDecimalZeroVsNewBigDecimalUnitTest {
|
||||
@Test
|
||||
void whenComparingZeroAndNewBigDecimal_thenGetExpectedResult() {
|
||||
BigDecimal bd1 = new BigDecimal("42.00");
|
||||
BigDecimal bd2 = new BigDecimal("42.0000");
|
||||
assertEquals(0, bd1.compareTo(bd2));
|
||||
|
||||
assertNotEquals(bd1, bd2);
|
||||
|
||||
BigDecimal zero0 = new BigDecimal(0);
|
||||
assertNotEquals(zero0, new BigDecimal("0.000"));
|
||||
|
||||
BigDecimal zero = BigDecimal.ZERO;
|
||||
assertEquals(zero, zero0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenCallingBigDecimalZero_thenAlwaysGetTheSameObject() {
|
||||
BigDecimal z1 = BigDecimal.ZERO;
|
||||
BigDecimal z2 = BigDecimal.ZERO;
|
||||
assertSame(z1, z2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenCallingNewBigDecimal_thenAlwaysGetTheSameObject() {
|
||||
BigDecimal z1 = new BigDecimal(0);
|
||||
BigDecimal z2 = new BigDecimal(0);
|
||||
assertNotSame(z1, z2);
|
||||
}
|
||||
|
||||
}
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
package com.baeldung.doubleisint;
|
||||
|
||||
import com.google.common.math.DoubleMath;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class CheckDoubleIsAnIntegerUnitTest {
|
||||
|
||||
boolean notNaNOrInfinity(double d) {
|
||||
return !(Double.isNaN(d) || Double.isInfinite(d));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenConvertingToInt_thenGetExpectedResult() {
|
||||
double d1 = 42.0D;
|
||||
boolean d1IsInteger = notNaNOrInfinity(d1) && (int) d1 == d1;
|
||||
assertTrue(d1IsInteger);
|
||||
|
||||
double d2 = 42.42D;
|
||||
boolean d2IsInteger = notNaNOrInfinity(d2) && (int) d2 == d2;
|
||||
assertFalse(d2IsInteger);
|
||||
|
||||
double d3 = 2.0D * Integer.MAX_VALUE;
|
||||
boolean d3IsInteger = notNaNOrInfinity(d3) && (int) d3 == d3;
|
||||
assertTrue(!d3IsInteger); // <-- fails if exceeding Integer's range
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingModuloOperator_thenGetExpectedResult() {
|
||||
double d1 = 42.0D;
|
||||
boolean d1IsInteger = notNaNOrInfinity(d1) && (d1 % 1) == 0;
|
||||
assertTrue(d1IsInteger);
|
||||
|
||||
double d2 = 42.42D;
|
||||
boolean d2IsInteger = notNaNOrInfinity(d2) && (d2 % 1) == 0;
|
||||
assertFalse(d2IsInteger);
|
||||
|
||||
double d3 = 2.0D * Integer.MAX_VALUE;
|
||||
boolean d3IsInteger = notNaNOrInfinity(d3) && (d3 % 1) == 0;
|
||||
assertTrue(d3IsInteger);
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void whenCheckingFloorOrCeilingValue_thenGetExpectedResult() {
|
||||
double d1 = 42.0D;
|
||||
boolean d1IsInteger = notNaNOrInfinity(d1) && Math.floor(d1) == d1;
|
||||
assertTrue(d1IsInteger);
|
||||
|
||||
double d2 = 42.42D;
|
||||
boolean d2IsInteger = notNaNOrInfinity(d2) && Math.floor(d2) == d2;
|
||||
assertFalse(d2IsInteger);
|
||||
|
||||
double d3 = 2.0D * Integer.MAX_VALUE;
|
||||
boolean d3IsInteger = notNaNOrInfinity(d3) && Math.floor(d3) == d3;
|
||||
assertTrue(d3IsInteger);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingGuava_thenGetExpectedResult() {
|
||||
double d1 = 42.0D;
|
||||
boolean d1IsInteger = DoubleMath.isMathematicalInteger(d1);
|
||||
assertTrue(d1IsInteger);
|
||||
|
||||
double d2 = 42.42D;
|
||||
boolean d2IsInteger = DoubleMath.isMathematicalInteger(d2);
|
||||
assertFalse(d2IsInteger);
|
||||
|
||||
double d3 = 2.0D * Integer.MAX_VALUE;
|
||||
boolean d3IsInteger = DoubleMath.isMathematicalInteger(d3);
|
||||
assertTrue(d3IsInteger);
|
||||
|
||||
boolean isInfinityInt = DoubleMath.isMathematicalInteger(Double.POSITIVE_INFINITY);
|
||||
assertFalse(isInfinityInt);
|
||||
|
||||
boolean isNanInt = DoubleMath.isMathematicalInteger(Double.NaN);
|
||||
assertFalse(isNanInt);
|
||||
}
|
||||
}
|
||||
@@ -4,3 +4,5 @@
|
||||
- [Convert int to Long in Java](https://www.baeldung.com/java-convert-int-long)
|
||||
- [How To Convert Double To Float In Java](https://www.baeldung.com/java-convert-double-float)
|
||||
- [Converting from float to BigDecimal in Java](https://www.baeldung.com/java-convert-float-bigdecimal)
|
||||
- [Convert Positive Integer to Negative and Vice Versa in Java](https://www.baeldung.com/java-negating-integer)
|
||||
- [Rounding Up a Number to Nearest Multiple of 5 in Java](https://www.baeldung.com/java-round-nearest-multiple-five)
|
||||
|
||||
+1
-1
@@ -23,7 +23,7 @@ public class AppUnitTest {
|
||||
soundRecorder.build(af);
|
||||
try {
|
||||
soundRecorder.start();
|
||||
Thread.sleep(20000);
|
||||
Thread.sleep(5000);
|
||||
soundRecorder.stop();
|
||||
} catch (InterruptedException ex) {
|
||||
fail("Exception: " + ex);
|
||||
|
||||
+2
-2
@@ -69,7 +69,7 @@ public class ProcessApiUnitTest {
|
||||
});
|
||||
});
|
||||
|
||||
Thread.sleep(10000);
|
||||
Thread.sleep(5000);
|
||||
|
||||
childProc = ProcessHandle.current().children();
|
||||
childProc.forEach(procHandle -> {
|
||||
@@ -100,7 +100,7 @@ public class ProcessApiUnitTest {
|
||||
private void waistCPU() throws NoSuchAlgorithmException {
|
||||
ArrayList<Integer> randArr = new ArrayList<Integer>(4096);
|
||||
SecureRandom sr = SecureRandom.getInstanceStrong();
|
||||
Duration somecpu = Duration.ofMillis(4200L);
|
||||
Duration somecpu = Duration.ofMillis(2000L);
|
||||
Instant end = Instant.now().plus(somecpu);
|
||||
while (Instant.now().isBefore(end)) {
|
||||
// System.out.println(sr.nextInt());
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<?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">
|
||||
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>
|
||||
|
||||
@@ -5,4 +5,5 @@ This module contains articles about core Java Security
|
||||
### Relevant Articles:
|
||||
- [Check if Certificate Is Self-Signed or CA-Signed With Java](https://www.baeldung.com/java-check-certificate-sign)
|
||||
- [Extract CN From X509 Certificate in Java](https://www.baeldung.com/java-extract-common-name-x509-certificate)
|
||||
- [Check Certificate Name and Alias in Keystore File](https://www.baeldung.com/java-keystore-check-certificate-name-alias)
|
||||
- More articles: [[<-- prev]](/core-java-modules/core-java-security-3)
|
||||
|
||||
@@ -71,7 +71,7 @@
|
||||
<dependency>
|
||||
<groupId>io.projectreactor</groupId>
|
||||
<artifactId>reactor-core</artifactId>
|
||||
<version>${io.reactor3.version}</version>
|
||||
<version>${reactor-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
@@ -121,7 +121,7 @@
|
||||
<rx.java2.version>2.2.2</rx.java2.version>
|
||||
<rx.java3.version>3.1.5</rx.java3.version>
|
||||
<io.varv.version>1.0.0-alpha-4</io.varv.version>
|
||||
<io.reactor3.version>3.5.1</io.reactor3.version>
|
||||
<reactor-core.version>3.6.0</reactor-core.version>
|
||||
<apache.commons.collection4.version>4.4</apache.commons.collection4.version>
|
||||
<cyclops.version>10.4.1</cyclops.version>
|
||||
</properties>
|
||||
|
||||
@@ -48,6 +48,11 @@
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>${commons-collections4.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.streams.firstmatchingelement;
|
||||
|
||||
public class User {
|
||||
|
||||
private String userName;
|
||||
private Integer userId;
|
||||
|
||||
public User(Integer userId, String userName) {
|
||||
this.userId = userId;
|
||||
this.userName = userName;
|
||||
}
|
||||
|
||||
public String getUserName() {
|
||||
return userName;
|
||||
}
|
||||
|
||||
public Integer getUserId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package com.baeldung.findfirstnullpointerexception;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Function;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class FindFirstNullPointerExceptionUnitTest {
|
||||
|
||||
private final List<String> inputs = Arrays.asList(null, "foo", "bar");
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void givenStream_whenCallingFindFirst_thenThrowNullPointerException() {
|
||||
Optional<String> firstElement = inputs.stream()
|
||||
.findFirst();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStream_whenUsingOfNullableBeforeFindFirst_thenCorrect() {
|
||||
Optional<String> firstElement = inputs.stream()
|
||||
.map(Optional::ofNullable)
|
||||
.findFirst()
|
||||
.flatMap(Function.identity());
|
||||
|
||||
assertTrue(firstElement.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStream_whenUsingFilterBeforeFindFirst_thenCorrect() {
|
||||
Optional<String> firstNonNullElement = inputs.stream()
|
||||
.filter(Objects::nonNull)
|
||||
.findFirst();
|
||||
|
||||
assertTrue(firstNonNullElement.isPresent());
|
||||
}
|
||||
|
||||
}
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
package com.baeldung.streams.firstmatchingelement;
|
||||
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import org.apache.commons.collections4.IterableUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.collect.Iterables;
|
||||
|
||||
public class FirstMatchingElementUnitTest {
|
||||
|
||||
private List<User> userList = List.of(new User(1, "David"), new User(2, "John"), new User(3, "Roger"), new User(4, "John"));
|
||||
private String searchName = "John";
|
||||
|
||||
@Test
|
||||
public void whenUsingStream_thenFindFirstMatchingUserIndex() {
|
||||
AtomicInteger counter = new AtomicInteger(-1);
|
||||
int index = userList.stream()
|
||||
.filter(user -> {
|
||||
counter.getAndIncrement();
|
||||
return searchName.equals(user.getUserName());
|
||||
})
|
||||
.mapToInt(user -> counter.get())
|
||||
.findFirst()
|
||||
.orElse(-1);
|
||||
|
||||
assertEquals(1, index);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingIntStream_thenFindFirstMatchingUserIndex() {
|
||||
int index = IntStream.range(0, userList.size() - 1)
|
||||
.filter(streamIndex -> searchName.equals(userList.get(streamIndex).getUserName()))
|
||||
.findFirst()
|
||||
.orElse(-1);
|
||||
assertEquals(1, index);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingTakeWhile_thenFindFirstMatchingUserIndex() {
|
||||
long predicateIndex = userList.stream()
|
||||
.takeWhile(user -> !user.getUserName().equals(searchName))
|
||||
.count();
|
||||
assertEquals(1, predicateIndex);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingTakeWhile_thenFindIndexFromNoMatchingElement() {
|
||||
List<User> userList = List.of(new User(1, "David"), new User(2, "Vick"), new User(3, "Roger"), new User(4, "James"));
|
||||
long predicateIndex = userList.stream()
|
||||
.takeWhile(user -> !user.getUserName().equals(searchName))
|
||||
.count();
|
||||
assertEquals(4, predicateIndex);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingGoogleGuava_thenFindFirstMatchingUserIndex() {
|
||||
int index = Iterables.indexOf(userList, user -> searchName.equals(user.getUserName()));
|
||||
assertEquals(1, index);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingApacheCommons_thenFindFirstMatchingUserIndex() {
|
||||
int index = IterableUtils.indexOf(userList, user -> searchName.equals(user.getUserName()));
|
||||
assertEquals(1, index);
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package com.baeldung.skipinputstream;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
|
||||
public class SkipInputStreamUnitTest {
|
||||
@Test
|
||||
public void givenInputStreamWithBytes_whenSkipBytes_thenRemainingBytes() throws IOException {
|
||||
byte[] inputData = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
|
||||
InputStream inputStream = new ByteArrayInputStream(inputData);
|
||||
|
||||
long bytesToSkip = 3;
|
||||
long skippedBytes = inputStream.skip(bytesToSkip);
|
||||
|
||||
assertArrayEquals(new byte[]{4, 5, 6, 7, 8, 9, 10}, readRemainingBytes(inputStream));
|
||||
|
||||
assert skippedBytes == bytesToSkip : "Incorrect number of bytes skipped";
|
||||
}
|
||||
|
||||
private byte[] readRemainingBytes(InputStream inputStream) throws IOException {
|
||||
byte[] buffer = new byte[inputStream.available()];
|
||||
int bytesRead = inputStream.read(buffer);
|
||||
if (bytesRead == -1) {
|
||||
throw new IOException("End of stream reached");
|
||||
}
|
||||
return buffer;
|
||||
}
|
||||
}
|
||||
@@ -44,10 +44,10 @@
|
||||
<artifactId>commons-codec</artifactId>
|
||||
<version>${commons-codec.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-core</artifactId>
|
||||
<version>${spring-core.version}</version>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-core</artifactId>
|
||||
<version>${spring-core.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
||||
@@ -72,7 +72,7 @@
|
||||
<spring-core.version>5.3.9</spring-core.version>
|
||||
<maven-artifact.version>3.6.3</maven-artifact.version>
|
||||
<gradle-core.version>6.1.1</gradle-core.version>
|
||||
<jackson-core.version>2.11.1</jackson-core.version>
|
||||
<jackson-core.version>2.16.0</jackson-core.version>
|
||||
<semver4j.version>3.1.0</semver4j.version>
|
||||
</properties>
|
||||
|
||||
|
||||
+1
-1
@@ -87,7 +87,7 @@ public class VersionComparisonUnitTest {
|
||||
assertTrue(version1_1_maven.compareTo(version1_1_gradle) < 0);
|
||||
|
||||
Version version1_1_snapshot = new Version(1, 1, 0, "snapshot", null, null);
|
||||
assertEquals(0, version1_1.compareTo(version1_1_snapshot));
|
||||
assertEquals(1, version1_1.compareTo(version1_1_snapshot));
|
||||
|
||||
assertTrue(version1_1_snapshot.isSnapshot());
|
||||
}
|
||||
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.stringmaxlength;
|
||||
|
||||
public class StringMaxLengthMain {
|
||||
|
||||
public static void main(String[] args) {
|
||||
displayRuntimeMaxStringLength();
|
||||
displayMaxStringLength();
|
||||
simulateStringOverflow();
|
||||
}
|
||||
|
||||
public static void simulateStringOverflow() {
|
||||
try {
|
||||
int maxLength = Integer.MAX_VALUE;
|
||||
char[] charArray = new char[maxLength];
|
||||
for (int i = 0; i < maxLength; i++) {
|
||||
charArray[i] = 'a';
|
||||
}
|
||||
String longString = new String(charArray);
|
||||
System.out.println("Successfully created a string of length: " + longString.length());
|
||||
} catch (OutOfMemoryError e) {
|
||||
System.err.println("Overflow error: Attempting to create a string longer than Integer.MAX_VALUE");
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static void displayRuntimeMaxStringLength() {
|
||||
long maxMemory = Runtime.getRuntime().maxMemory();
|
||||
System.out.println("Maximum String length based on available memory: " + (maxMemory));
|
||||
}
|
||||
|
||||
public static void displayMaxStringLength() {
|
||||
int maxStringLength = Integer.MAX_VALUE;
|
||||
System.out.println("Maximum String length based on Integer.MAX_VALUE: " + maxStringLength);
|
||||
}
|
||||
}
|
||||
+1
@@ -28,6 +28,7 @@ public class ComparePerformance {
|
||||
|
||||
@Benchmark
|
||||
public String benchmarkStringConcatenation() {
|
||||
strFinal = "";
|
||||
strFinal += strInitial;
|
||||
return strFinal;
|
||||
}
|
||||
|
||||
Binary file not shown.
@@ -6,3 +6,4 @@
|
||||
- [Validate UUID String in Java](https://www.baeldung.com/java-validate-uuid-string)
|
||||
- [Generate the Same UUID From a String in Java](https://www.baeldung.com/java-generate-same-uuid-from-string)
|
||||
- [Generating Time Based UUIDs](https://www.baeldung.com/java-generating-time-based-uuids)
|
||||
- [Generating Unique Positive long Using UUID in Java](https://www.baeldung.com/java-uuid-unique-long-generation)
|
||||
|
||||
@@ -59,16 +59,16 @@
|
||||
<module>core-java-lang-oop-constructors-2</module>
|
||||
<module>core-java-methods</module>
|
||||
<module>core-java-networking-3</module>
|
||||
<module>core-java-os</module>
|
||||
<!--<module>core-java-os</module>--> <!-- failing after upgrading to jdk17 -->
|
||||
<module>core-java-perf-2</module>
|
||||
<module>core-java-streams-4</module>
|
||||
<module>core-java-streams-5</module>
|
||||
<module>core-java-streams-collect</module>
|
||||
<module>core-java-streams-maps</module>
|
||||
<module>core-java-string-algorithms-3</module>
|
||||
<module>core-java-string-operations-3</module>
|
||||
<!--<module>core-java-string-operations-3</module>--> <!-- failing after upgrading to jdk17 -->
|
||||
<module>core-java-string-operations-4</module>
|
||||
<module>core-java-string-operations-5</module>
|
||||
<!--<module>core-java-string-operations-5</module>--> <!-- failing after upgrading to jdk17 -->
|
||||
<!--<module>core-java-strings</module> Failing test cases JAVA-24414-->
|
||||
<module>core-java-time-measurements</module>
|
||||
<module>core-java-annotations</module>
|
||||
@@ -123,13 +123,13 @@
|
||||
<module>core-java-io</module>
|
||||
<module>core-java-io-2</module>
|
||||
<module>core-java-io-3</module>
|
||||
<module>core-java-io-4</module>
|
||||
<!--<module>core-java-io-4</module>--> <!-- failing after upgrading to jdk17 -->
|
||||
<module>core-java-io-5</module>
|
||||
<module>core-java-io-apis</module>
|
||||
<module>core-java-io-apis-2</module>
|
||||
<module>core-java-io-conversions</module>
|
||||
<module>core-java-jar</module>
|
||||
<module>core-java-jndi</module>
|
||||
<!--<module>core-java-jndi</module>--> <!-- failing after upgrading to jdk17 -->
|
||||
<module>core-java-jvm</module>
|
||||
<module>core-java-jvm-2</module>
|
||||
<module>core-java-jvm-3</module>
|
||||
@@ -144,11 +144,11 @@
|
||||
<module>core-java-lang-oop-constructors</module>
|
||||
<module>core-java-lang-oop-patterns</module>
|
||||
<module>core-java-lang-oop-generics</module>
|
||||
<module>core-java-lang-oop-modifiers</module>
|
||||
<!--<module>core-java-lang-oop-modifiers</module>--> <!-- failing after upgrading to jdk17 -->
|
||||
<module>core-java-lang-oop-types</module>
|
||||
<module>core-java-lang-oop-types-2</module>
|
||||
<module>core-java-lang-oop-inheritance</module>
|
||||
<module>core-java-lang-oop-methods</module>
|
||||
<!--<module>core-java-lang-oop-methods</module>--> <!-- failing after upgrading to jdk17 -->
|
||||
<module>core-java-lang-oop-others</module>
|
||||
<module>core-java-lang-operators</module>
|
||||
<module>core-java-lang-operators-2</module>
|
||||
@@ -166,6 +166,7 @@
|
||||
<module>core-java-numbers-4</module>
|
||||
<module>core-java-numbers-5</module>
|
||||
<module>core-java-numbers-6</module>
|
||||
<module>core-java-numbers-7</module>
|
||||
<module>core-java-optional</module>
|
||||
<module>core-java-perf</module>
|
||||
<module>core-java-properties</module>
|
||||
@@ -184,8 +185,8 @@
|
||||
<module>core-java-string-algorithms</module>
|
||||
<module>core-java-string-algorithms-2</module>
|
||||
<module>core-java-string-apis</module>
|
||||
<!--<module>core-java-string-apis-2</module>--> <!-- failing after upgrading to jdk17 -->
|
||||
<module>core-java-swing</module>
|
||||
<module>core-java-string-apis-2</module>
|
||||
<module>core-java-string-conversions</module>
|
||||
<module>core-java-string-conversions-2</module>
|
||||
<module>core-java-string-conversions-3</module>
|
||||
@@ -225,5 +226,4 @@
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
</project>
|
||||
|
||||
Reference in New Issue
Block a user