Merge remote-tracking branch 'upstream/master' into feature/BAEL-7086-ResultSetToMap

This commit is contained in:
Niket Agrawal 2023-10-29 01:45:23 +05:30
commit 197940d47c
231 changed files with 1069 additions and 130 deletions

View File

@ -5,6 +5,5 @@ This module contains articles about various Amazon Web Services (AWS) such as EC
### Relevant articles
- [Managing EC2 Instances in Java](https://www.baeldung.com/ec2-java)
- [Integration Testing with a Local DynamoDB Instance](https://www.baeldung.com/dynamodb-local-integration-tests)
- [Managing Amazon SQS Queues in Java](https://www.baeldung.com/aws-queues-java)
- [Guide to AWS Aurora RDS with Java](https://www.baeldung.com/aws-aurora-rds-java)

View File

@ -11,5 +11,5 @@ This module contains articles about Java 8 core features
- [Finding Min/Max in an Array with Java](https://www.baeldung.com/java-array-min-max)
- [Internationalization and Localization in Java 8](https://www.baeldung.com/java-8-localization)
- [Generalized Target-Type Inference in Java](https://www.baeldung.com/java-generalized-target-type-inference)
- [Monads in Java](https://www.baeldung.com/java-monads)
- [Monads in Java Optional](https://www.baeldung.com/java-monads)
- [[More -->]](/core-java-modules/core-java-8-2)

View File

@ -0,0 +1,5 @@
## Core Java Arrays - Basic Operations
This module contains articles about Java array fundamentals. They assume no previous background knowledge on working with arrays.
### Relevant Articles:

View File

@ -0,0 +1,16 @@
<?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-arrays-operations-basic-2</artifactId>
<name>core-java-arrays-operations-basic-2</name>
<packaging>jar</packaging>
<parent>
<artifactId>core-java-modules</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
</project>

View File

@ -0,0 +1,269 @@
package com.baeldung.array.mismatch;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.Arrays;
import java.util.Comparator;
import org.junit.jupiter.api.Test;
class ArrayMismatchUnitTest {
@Test
void givenTwoArraysWithACommonPrefix_whenMismatch_thenIndexOfFirstMismatch() {
int[] firstArray = {1, 2, 3, 4, 5};
int[] secondArray = {1, 2, 3, 5, 8};
assertEquals(3, Arrays.mismatch(firstArray, secondArray));
}
@Test
void givenTwoIdenticalArrays_whenMismatch_thenMinusOne() {
int[] firstArray = {1, 2, 3, 4, 5};
int[] secondArray = {1, 2, 3, 4, 5};
assertEquals(-1, Arrays.mismatch(firstArray, secondArray));
}
@Test
void givenFirstArrayIsAPrefixOfTheSecond_whenMismatch_thenFirstArrayLength() {
int[] firstArray = {1, 2, 3, 4, 5};
int[] secondArray = {1, 2, 3, 4, 5, 6, 7, 8, 9};
assertEquals(firstArray.length, Arrays.mismatch(firstArray, secondArray));
}
@Test
void givenNoCommonPrefix_whenMismatch_thenZero() {
int[] firstArray = {1, 2, 3, 4, 5};
int[] secondArray = {9, 8, 7};
assertEquals(0, Arrays.mismatch(firstArray, secondArray));
}
@Test
void givenAtLeastANullArray_whenMismatch_thenThrowsNullPointerException() {
int[] firstArray = null;
int[] secondArray = {1, 2, 3, 4, 5};
assertThrows(NullPointerException.class, () -> Arrays.mismatch(firstArray, secondArray));
assertThrows(NullPointerException.class, () -> Arrays.mismatch(secondArray, firstArray));
assertThrows(NullPointerException.class, () -> Arrays.mismatch(firstArray, firstArray));
}
@Test
void givenExactlyOneAnEmptyArray_whenMismatch_thenZero() {
int[] firstArray = {};
int[] secondArray = {1, 2, 3};
assertEquals(0, Arrays.mismatch(firstArray, secondArray));
assertEquals(0, Arrays.mismatch(secondArray, firstArray));
}
@Test
void givenTwoEmptyArrays_whenMismatch_thenMinusOne() {
assertEquals(-1, Arrays.mismatch(new int[] {}, new int[] {}));
}
@Test
void givenTwoSubArraysWithACommonPrefix_whenMismatch_thenIndexOfFirstMismatch() {
int[] firstArray = {1, 2, 3, 4, 5};
int[] secondArray = {0, 1, 2, 3, 5, 8};
assertEquals(3, Arrays.mismatch(firstArray, 0, 4, secondArray, 1, 6));
}
@Test
void givenTwoIdenticalSubArrays_whenMismatch_thenMinusOne() {
int[] firstArray = {0, 0, 1, 2};
int[] secondArray = {0, 1, 2, 3, 4};
assertEquals(-1, Arrays.mismatch(firstArray, 2, 4, secondArray, 1, 3));
}
@Test
void givenFirstSubArrayIsAPrefixOfTheSecond_whenMismatch_thenFirstArrayLength() {
int[] firstArray = {2, 3, 4, 5, 4, 3, 2};
int[] secondArray = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
assertEquals(4, Arrays.mismatch(firstArray, 0, 4, secondArray, 2, 9));
}
@Test
void givenNoCommonPrefixForSubArrays_whenMismatch_thenZero() {
int[] firstArray = {0, 0, 0, 0, 0};
int[] secondArray = {9, 8, 7, 6, 5};
assertEquals(0, Arrays.mismatch(firstArray, 1, 2, secondArray, 1, 2));
}
@Test
void givenAtLeastANullSubArray_whenMismatch_thenThrowsNullPointerException() {
int[] firstArray = null;
int[] secondArray = {1, 2, 3, 4, 5};
assertThrows(NullPointerException.class, () -> Arrays.mismatch(firstArray, 0, 1, secondArray, 0, 1));
assertThrows(NullPointerException.class, () -> Arrays.mismatch(secondArray, 0, 1, firstArray, 0, 1));
assertThrows(NullPointerException.class, () -> Arrays.mismatch(firstArray, 0, 1, firstArray, 0, 1));
}
@Test
void givenExactlyOneEmptySubArray_whenMismatch_thenZero() {
int[] firstArray = {1};
int[] secondArray = {1, 2, 3};
assertEquals(0, Arrays.mismatch(firstArray, 0, 0, secondArray, 0, 2));
assertEquals(0, Arrays.mismatch(firstArray, 0, 1, secondArray, 2, 2));
}
@Test
void givenTwoEmptySubArrays_whenMismatch_thenMinusOne() {
int[] firstArray = {1};
int[] secondArray = {1, 2, 3};
assertEquals(-1, Arrays.mismatch(firstArray, 0, 0, secondArray, 2, 2));
}
@Test
void givenToIndexGreaterThanFromIndex_whenMismatch_thenThrowsIllegalArgumentException() {
int[] firstArray = {2, 3, 4, 5, 4, 3, 2};
int[] secondArray = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
assertThrows(IllegalArgumentException.class, () -> Arrays.mismatch(firstArray, 4, 2, secondArray, 0, 6));
assertThrows(IllegalArgumentException.class, () -> Arrays.mismatch(firstArray, 2, 3, secondArray, 6, 0));
}
@Test
void givenIllegalIndexes_whenMismatch_thenThrowsArrayIndexOutOfBoundsException() {
int[] firstArray = {2, 3, 4, 5, 4, 3, 2};
int[] secondArray = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
assertThrows(ArrayIndexOutOfBoundsException.class, () -> Arrays.mismatch(firstArray, -1, 2, secondArray, 0, 6));
assertThrows(ArrayIndexOutOfBoundsException.class, () -> Arrays.mismatch(firstArray, 0, 8, secondArray, 0, 6));
assertThrows(ArrayIndexOutOfBoundsException.class, () -> Arrays.mismatch(firstArray, 2, 3, secondArray, -5, 0));
assertThrows(ArrayIndexOutOfBoundsException.class, () -> Arrays.mismatch(firstArray, 2, 3, secondArray, 11, 12));
}
@Test
void givenTwoStringArraysAndAComparator_whenMismatch_thenIndexOfFirstMismatch() {
String[] firstArray = {"one", "two", "three"};
String[] secondArray = {"ONE", "TWO", "FOUR"};
Comparator<String> comparator = String.CASE_INSENSITIVE_ORDER;
assertEquals(2, Arrays.mismatch(firstArray, secondArray, comparator));
}
@Test
void givenTwoIdenticalStringArraysForTheComparator_whenMismatch_thenMinusOne() {
String[] firstArray = {"one", "two", "three"};
String[] secondArray = {"ONE", "TWO", "THREE"};
Comparator<String> comparator = String.CASE_INSENSITIVE_ORDER;
assertEquals(-1, Arrays.mismatch(firstArray, secondArray, comparator));
}
@Test
void givenFirstStringArrayIsAPrefixOfTheSecondForTheComparator_whenMismatch_thenFirstArrayLength() {
String[] firstArray = {"one", "two", "three"};
String[] secondArray = {"ONE", "TWO", "THREE", "FOUR", "FIVE"};
Comparator<String> comparator = String.CASE_INSENSITIVE_ORDER;
assertEquals(firstArray.length, Arrays.mismatch(firstArray, secondArray, comparator));
}
@Test
void givenNoCommonPrefixForTheComparator_whenMismatch_thenZero() {
String[] firstArray = {"one", "two", "three"};
String[] secondArray = {"six", "seven", "eight"};
Comparator<String> comparator = String.CASE_INSENSITIVE_ORDER;
assertEquals(0, Arrays.mismatch(firstArray, secondArray, comparator));
}
@Test
void givenAtLeastANullArrayOrNullComparator_whenMismatch_thenThrowsNullPointerException() {
String[] firstArray = null;
String[] secondArray = {"one"};
Comparator<String> comparator = String.CASE_INSENSITIVE_ORDER;
assertThrows(NullPointerException.class, () -> Arrays.mismatch(firstArray, secondArray, comparator));
assertThrows(NullPointerException.class, () -> Arrays.mismatch(secondArray, firstArray, comparator));
assertThrows(NullPointerException.class, () -> Arrays.mismatch(secondArray, secondArray, null));
}
@Test
void givenExactlyOneAnEmptyArrayAndAComparator_whenMismatch_thenZero() {
String[] firstArray = {};
String[] secondArray = {"one"};
Comparator<String> comparator = String.CASE_INSENSITIVE_ORDER;
assertEquals(0, Arrays.mismatch(firstArray, secondArray, comparator));
assertEquals(0, Arrays.mismatch(secondArray, firstArray, comparator));
}
@Test
void givenTwoEmptyStringArraysForTheComparator_whenMismatch_thenMinusOne() {
assertEquals(-1, Arrays.mismatch(new String[] {}, new String[] {}, String.CASE_INSENSITIVE_ORDER));
}
@Test
void givenTwoStringSubarraysAndAComparator_whenMismatch_thenIndexOfFirstMismatch() {
String[] firstArray = {"one", "two", "three", "four"};
String[] secondArray = {"ZERO", "ONE", "TWO", "FOUR", "EIGHT", "SIXTEEN"};
Comparator<String> comparator = String.CASE_INSENSITIVE_ORDER;
assertEquals(2, Arrays.mismatch(firstArray, 0, 4, secondArray, 1, 3, comparator));
}
@Test
void givenTwoIdenticalStringSubArraysForTheComparator_whenMismatch_thenMinusOne() {
String[] firstArray = {"zero", "zero", "one", "two"};
String[] secondArray = {"zero", "one", "two", "three", "four"};
Comparator<String> comparator = String.CASE_INSENSITIVE_ORDER;
assertEquals(-1, Arrays.mismatch(firstArray, 2, 4, secondArray, 1, 3, comparator));
}
@Test
void givenFirstSubArrayIsAPrefixOfTheSecondForTheComparator_whenMismatch_thenFirstArrayLength() {
String[] firstArray = {"two", "three", "four", "five", "four", "three", "two"};
String[] secondArray = {"ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "EIGHT", "NINE", "TEN"};
Comparator<String> comparator = String.CASE_INSENSITIVE_ORDER;
assertEquals(4, Arrays.mismatch(firstArray, 0, 4, secondArray, 2, 9, comparator));
}
@Test
void givenNoCommonPrefixForSubArraysForTheComparator_whenMismatch_thenZero() {
String[] firstArray = {"zero", "one"};
String[] secondArray = {"TEN", "ELEVEN", "TWELVE"};
Comparator<String> comparator = String.CASE_INSENSITIVE_ORDER;
assertEquals(0, Arrays.mismatch(firstArray, 1, 2, secondArray, 1, 2, comparator));
}
@Test
void givenAtLeastANullSubArrayOrNullComparator_whenMismatch_thenThrowsNullPointerException() {
String[] firstArray = null;
String[] secondArray = {"ONE", "TWO", "THREE", "FOUR", "FIVE"};
Comparator<String> comparator = String.CASE_INSENSITIVE_ORDER;
assertThrows(NullPointerException.class, () -> Arrays.mismatch(firstArray, 0, 1, secondArray, 0, 1, comparator));
assertThrows(NullPointerException.class, () -> Arrays.mismatch(secondArray, 0, 1, firstArray, 0, 1, comparator));
assertThrows(NullPointerException.class, () -> Arrays.mismatch(firstArray, 0, 1, firstArray, 0, 1, comparator));
assertThrows(NullPointerException.class, () -> Arrays.mismatch(secondArray, 0, 1, secondArray, 0, 1, null));
}
@Test
void givenExactlyOneEmptySubArrayAndAComparator_whenMismatch_thenZero() {
String[] firstArray = {"one"};
String[] secondArray = {"ONE", "TWO", "THREE"};
Comparator<String> comparator = String.CASE_INSENSITIVE_ORDER;
assertEquals(0, Arrays.mismatch(firstArray, 0, 0, secondArray, 0, 2, comparator));
assertEquals(0, Arrays.mismatch(firstArray, 0, 1, secondArray, 2, 2, comparator));
}
@Test
void givenTwoEmptySubArraysAndAComparator_whenMismatch_thenMinusOne() {
String[] firstArray = {"one"};
String[] secondArray = {"ONE", "TWO", "THREE"};
Comparator<String> comparator = String.CASE_INSENSITIVE_ORDER;
assertEquals(-1, Arrays.mismatch(firstArray, 0, 0, secondArray, 2, 2, comparator));
}
@Test
void givenToIndexGreaterThanFromIndexAndAComparator_whenMismatch_thenThrowsIllegalArgumentException() {
String[] firstArray = {"two", "three", "four", "five", "four", "three", "two"};
String[] secondArray = {"ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "EIGHT", "NINE", "TEN"};
Comparator<String> comparator = String.CASE_INSENSITIVE_ORDER;
assertThrows(IllegalArgumentException.class, () -> Arrays.mismatch(firstArray, 4, 2, secondArray, 0, 6, comparator));
assertThrows(IllegalArgumentException.class, () -> Arrays.mismatch(firstArray, 2, 3, secondArray, 6, 0, comparator));
}
@Test
void givenIllegalIndexesAndAComparator_whenMismatch_thenThrowsArrayIndexOutOfBoundsException() {
String[] firstArray = {"two", "three", "four", "five", "four", "three", "two"};
String[] secondArray = {"ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "EIGHT", "NINE", "TEN"};
Comparator<String> comparator = String.CASE_INSENSITIVE_ORDER;
assertThrows(ArrayIndexOutOfBoundsException.class, () -> Arrays.mismatch(firstArray, -1, 2, secondArray, 0, 6, comparator));
assertThrows(ArrayIndexOutOfBoundsException.class, () -> Arrays.mismatch(firstArray, 0, 8, secondArray, 0, 6, comparator));
assertThrows(ArrayIndexOutOfBoundsException.class, () -> Arrays.mismatch(firstArray, 2, 3, secondArray, -5, 0, comparator));
assertThrows(ArrayIndexOutOfBoundsException.class, () -> Arrays.mismatch(firstArray, 2, 3, secondArray, 11, 12, comparator));
}
}

View File

@ -12,7 +12,7 @@ public class RemoveQueueElementsUnitTest {
@Test
public void givenQueueWithEvenAndOddNumbers_whenRemovingEvenNumbers_thenOddNumbersRemain() {
Queue<Integer> queue = new LinkedList<>();
Queue<Integer> evenElementsQueue = new LinkedList<>();
Queue<Integer> oddElementsQueue = new LinkedList<>();
queue.add(1);
queue.add(2);
queue.add(3);
@ -22,14 +22,14 @@ public class RemoveQueueElementsUnitTest {
while (queue.peek() != null) {
int element = queue.remove();
if (element % 2 != 0) {
evenElementsQueue.add(element);
oddElementsQueue.add(element);
}
}
assertEquals(3, evenElementsQueue.size());
assertTrue(evenElementsQueue.contains(1));
assertTrue(evenElementsQueue.contains(3));
assertTrue(evenElementsQueue.contains(5));
assertEquals(3, oddElementsQueue.size());
assertTrue(oddElementsQueue.contains(1));
assertTrue(oddElementsQueue.contains(3));
assertTrue(oddElementsQueue.contains(5));
}
@Test

View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [Why wait() Requires Synchronization?](https://www.baeldung.com/java-wait-necessary-synchronization)

View File

@ -0,0 +1,63 @@
package com.baeldung.concurrent.completablefuture.retry;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import java.util.function.Supplier;
public class RetryCompletableFuture {
public static <T> CompletableFuture<T> retryTask(Supplier<T> supplier, int maxRetries) {
Supplier<T> retryableSupplier = retryFunction(supplier, maxRetries);
return CompletableFuture.supplyAsync(retryableSupplier);
}
static <T> Supplier<T> retryFunction(Supplier<T> supplier, int maxRetries) {
return () -> {
int retries = 0;
while (retries < maxRetries) {
try {
return supplier.get();
} catch (Exception e) {
retries++;
}
}
throw new IllegalStateException(String.format("Task failed after %s attempts", maxRetries));
};
}
public static <T> CompletableFuture<T> retryUnsafe(Supplier<T> supplier, int maxRetries) {
CompletableFuture<T> cf = CompletableFuture.supplyAsync(supplier);
sleep(100l);
for (int i = 0; i < maxRetries; i++) {
cf = cf.exceptionally(__ -> supplier.get());
}
return cf;
}
public static <T> CompletableFuture<T> retryNesting(Supplier<T> supplier, int maxRetries) {
CompletableFuture<T> cf = CompletableFuture.supplyAsync(supplier);
sleep(100);
for (int i = 0; i < maxRetries; i++) {
cf = cf.thenApply(CompletableFuture::completedFuture)
.exceptionally(__ -> CompletableFuture.supplyAsync(supplier))
.thenCompose(Function.identity());
}
return cf;
}
public static <T> CompletableFuture<T> retryExceptionallyAsync(Supplier<T> supplier, int maxRetries) {
CompletableFuture<T> cf = CompletableFuture.supplyAsync(supplier);
sleep(100);
for (int i = 0; i < maxRetries; i++) {
cf = cf.exceptionallyAsync(__ -> supplier.get());
}
return cf;
}
private static void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}

View File

@ -0,0 +1,120 @@
package com.baeldung.concurrent.completablefuture.retry;
import static com.baeldung.concurrent.completablefuture.retry.RetryCompletableFuture.retryExceptionallyAsync;
import static com.baeldung.concurrent.completablefuture.retry.RetryCompletableFuture.retryNesting;
import static com.baeldung.concurrent.completablefuture.retry.RetryCompletableFuture.retryTask;
import static com.baeldung.concurrent.completablefuture.retry.RetryCompletableFuture.retryUnsafe;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class RetryCompletableFutureUnitTest {
private AtomicInteger retriesCounter = new AtomicInteger(0);
@BeforeEach
void beforeEach() {
retriesCounter.set(0);
}
@Test
void whenRetryingTask_thenReturnsCorrectlyAfterFourInvocations() {
Supplier<Integer> codeToRun = () -> failFourTimesThenReturn(100);
CompletableFuture<Integer> result = retryTask(codeToRun, 10);
assertThat(result.join()).isEqualTo(100);
assertThat(retriesCounter).hasValue(4);
}
@Test
void whenRetryingTask_thenThrowsExceptionAfterThreeInvocations() {
Supplier<Integer> codeToRun = () -> failFourTimesThenReturn(100);
CompletableFuture<Integer> result = retryTask(codeToRun, 3);
assertThatThrownBy(result::join)
.isInstanceOf(CompletionException.class)
.hasMessageContaining("IllegalStateException: Task failed after 3 attempts");
}
@Test
void whenRetryingExceptionally_thenReturnsCorrectlyAfterFourInvocations() {
Supplier<Integer> codeToRun = () -> failFourTimesThenReturn(100);
CompletableFuture<Integer> result = retryUnsafe(codeToRun, 10);
assertThat(result.join()).isEqualTo(100);
assertThat(retriesCounter).hasValue(4);
}
@Test
void whenRetryingExceptionally_thenThrowsExceptionAfterThreeInvocations() {
Supplier<Integer> codeToRun = () -> failFourTimesThenReturn(100);
CompletableFuture<Integer> result = retryUnsafe(codeToRun, 3);
assertThatThrownBy(result::join)
.isInstanceOf(CompletionException.class)
.hasMessageContaining("RuntimeException: task failed for 3 time(s)");
}
@Test
void whenRetryingExceptionallyAsync_thenReturnsCorrectlyAfterFourInvocations() {
Supplier<Integer> codeToRun = () -> failFourTimesThenReturn(100);
CompletableFuture<Integer> result = retryExceptionallyAsync(codeToRun, 10);
assertThat(result.join()).isEqualTo(100);
assertThat(retriesCounter).hasValue(4);
}
@Test
void whenRetryingExceptionallyAsync_thenThrowsExceptionAfterThreeInvocations() {
Supplier<Integer> codeToRun = () -> failFourTimesThenReturn(100);
CompletableFuture<Integer> result = retryExceptionallyAsync(codeToRun, 3);
assertThatThrownBy(result::join)
.isInstanceOf(CompletionException.class)
.hasMessageContaining("RuntimeException: task failed for 3 time(s)");
}
@Test
void whenRetryingNesting_thenReturnsCorrectlyAfterFourInvocations() {
Supplier<Integer> codeToRun = () -> failFourTimesThenReturn(100);
CompletableFuture<Integer> result = retryNesting(codeToRun, 10);
assertThat(result.join()).isEqualTo(100);
assertThat(retriesCounter).hasValue(4);
}
@Test
void whenRetryingNesting_thenThrowsExceptionAfterThreeInvocations() {
Supplier<Integer> codeToRun = () -> failFourTimesThenReturn(100);
CompletableFuture<Integer> result = retryNesting(codeToRun, 3);
assertThatThrownBy(result::join)
.isInstanceOf(CompletionException.class)
.hasMessageContaining("RuntimeException: task failed for 3 time(s)");
}
int failFourTimesThenReturn(int returnValue) {
int retryNr = retriesCounter.get();
System.out.println(String.format("invocation: %s, thread: %s", retryNr, Thread.currentThread().getName()));
if (retryNr < 4) {
retriesCounter.set(retryNr + 1);
throw new RuntimeException(String.format("task failed for %s time(s)", retryNr));
}
return returnValue;
}
}

View File

@ -0,0 +1,73 @@
package com.baeldung.truncatedouble;
import static org.junit.Assert.assertEquals;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import org.junit.Test;
public class TruncateDoubleUnitTest {
@Test
public void givenADouble_whenUsingDecimalFormat_truncateToTwoDecimalPlaces() {
DecimalFormat df = new DecimalFormat("#.##");
df.setRoundingMode(RoundingMode.DOWN);
double value = 1.55555555;
String truncated = df.format(value);
assertEquals("1.55", truncated);
double negativeValue = -1.55555555;
String negativeTruncated = df.format(negativeValue);
assertEquals("-1.55", negativeTruncated);
}
@Test
public void givenADouble_whenUsingNumberFormat_truncateToTwoDecimalPlaces() {
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(2);
nf.setRoundingMode(RoundingMode.DOWN);
double value = 1.55555555;
String truncated = nf.format(value);
assertEquals("1.55", truncated);
double negativeValue = -1.55555555;
String negativeTruncated = nf.format(negativeValue);
assertEquals("-1.55", negativeTruncated);
}
@Test
public void givenADouble_whenUsingBigDecimal_truncateToTwoDecimalPlaces() {
BigDecimal positive = new BigDecimal(2.555555).setScale(2, RoundingMode.DOWN);
BigDecimal negative = new BigDecimal(-2.555555).setScale(2, RoundingMode.DOWN);
assertEquals("2.55", positive.toString());
assertEquals("-2.55", negative.toString());
}
@Test
public void givenADouble_whenUsingMath_truncateToTwoDecimalPlaces() {
double positive = 1.55555555;
double truncated = Math.floor(positive * 100) / 100;
assertEquals("1.55", String.valueOf(truncated));
double negative = -1.55555555;
double negativeTruncated = Math.ceil(negative * 100) / 100;
assertEquals("-1.55", String.valueOf(negativeTruncated));
}
@Test
public void givenADouble_whenUsingStringFormat_truncateToTwoDecimalPlaces() {
double positive = 1.55555555;
String truncated = String.format("%.2f", positive);
assertEquals("1.56", truncated);
double negative = -1.55555555;
String negativeTruncated = String.format("%.2f", negative);
assertEquals("-1.56", negativeTruncated);
}
}

View File

@ -7,23 +7,27 @@ public class FloatDoubleConversionsTest {
@Test
public void whenDoubleType_thenFloatTypeSuccess(){
double interestRatesYearly = 13.333333333333334;
double interestRatesYearly = 13.333333333333333;
float interest = (float) interestRatesYearly;
Assert.assertEquals(13.333333f, interest, 0.000004f);
System.out.println(interest); //13.333333
Assert.assertEquals(13.333333f, interest, 0.000001f);
Double monthlyRates = 2.111111111111112;
Double monthlyRates = 2.111111111111111;
float rates = monthlyRates.floatValue();
Assert.assertEquals(2.1111112f, rates, 0.00000013);
System.out.println(rates); //2.1111112
Assert.assertEquals(2.1111111f, rates, 0.0000001f);
}
@Test
public void whenFloatType_thenDoubleTypeSuccess(){
float gradeAverage =2.05f;
double average = gradeAverage;
Assert.assertEquals(2.05, average, 0.06);
System.out.println(average); //2.049999952316284
Assert.assertEquals(2.05, average, 0.01);
Float monthlyRates = 2.1111112f;
Float monthlyRates = 2.1111111f;
Double rates = monthlyRates.doubleValue();
Assert.assertEquals(2.11111112, rates, 0.0000002);//true
System.out.println(rates); //2.1111111640930176
Assert.assertEquals(2.11111111, rates, 0.0000001);//true
}
}

View File

@ -1,2 +1,3 @@
### Relevant Articles:
[How to Center Text Output in Java](https://www.baeldung.com/java-center-text-output)

View File

@ -65,7 +65,7 @@
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<apache.commons.lang3.version>3.12.0</apache.commons.lang3.version>
<apache.commons.lang3.version>3.13.0</apache.commons.lang3.version>
<commons-text.version>1.10.0</commons-text.version>
</properties>

View File

@ -0,0 +1,40 @@
package com.baeldung.capitalizefirstcharactereachword;
import java.util.Arrays;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
class CapitalizeFirstCharacterEachWordUtils {
static String usingCharacterToUpperCaseMethod(String input) {
if (input == null || input.isEmpty()) {
return null;
}
return Arrays.stream(input.split("\\s+"))
.map(word -> Character.toUpperCase(word.charAt(0)) + word.substring(1))
.collect(Collectors.joining(" "));
}
static String usingStringToUpperCaseMethod(String input) {
if (input == null || input.isEmpty()) {
return null;
}
return Arrays.stream(input.split("\\s+"))
.map(word -> word.substring(0, 1).toUpperCase() + word.substring(1))
.collect(Collectors.joining(" "));
}
static String usingStringUtilsClass(String input) {
if (input == null || input.isEmpty()) {
return null;
}
return Arrays.stream(input.split("\\s+"))
.map(StringUtils::capitalize)
.collect(Collectors.joining(" "));
}
}

View File

@ -0,0 +1,77 @@
package com.baeldung.strcontainsnumber;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import com.google.common.base.CharMatcher;
public class StrContainsNumberUtils {
static boolean checkUsingMatchesMethod(String input) {
if (input == null || input.isEmpty()) {
return false;
}
return input.matches(".*\\d.*");
}
static boolean checkUsingPatternClass(String input) {
if (input == null || input.isEmpty()) {
return false;
}
return Pattern.compile(".*\\d.*")
.matcher(input)
.matches();
}
static boolean checkUsingReplaceAllMethod(String input) {
if (input == null || input.isEmpty()) {
return false;
}
String result = input.replaceAll("\\d", "");
return result.length() != input.length();
}
static boolean checkUsingIsDigitMethod(String input) {
if (input == null || input.isEmpty()) {
return false;
}
for (char c : input.toCharArray()) {
if (Character.isDigit(c)) {
return true;
}
}
return false;
}
static boolean checkUsingStreamApi(String input) {
if (input == null || input.isEmpty()) {
return false;
}
return input.chars()
.anyMatch(Character::isDigit);
}
static boolean checkUsingApacheCommonsLang(String input) {
String result = StringUtils.getDigits(input);
return result != null && !result.isEmpty();
}
static boolean checkUsingGuava(String input) {
if (input == null || input.isEmpty()) {
return false;
}
String result = CharMatcher.forPredicate(Character::isDigit)
.retainFrom(input);
return !result.isEmpty();
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.capitalizefirstcharactereachword;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.apache.commons.text.WordUtils;
import org.junit.jupiter.api.Test;
class CapitalizeFirstCharacterEachWordUtilsUnitTest {
@Test
void givenString_whenUsingCharacterToUpperCaseMethod_thenCapitalizeFirstCharacter() {
String input = "hello baeldung visitors";
assertEquals("Hello Baeldung Visitors", CapitalizeFirstCharacterEachWordUtils.usingCharacterToUpperCaseMethod(input));
}
@Test
void givenString_whenUsingSubstringMethod_thenCapitalizeFirstCharacter() {
String input = "Hi, my name is azhrioun";
assertEquals("Hi, My Name Is Azhrioun", CapitalizeFirstCharacterEachWordUtils.usingStringToUpperCaseMethod(input));
}
@Test
void givenString_whenUsingStringUtilsClass_thenCapitalizeFirstCharacter() {
String input = "life is short the world is wide";
assertEquals("Life Is Short The World Is Wide", CapitalizeFirstCharacterEachWordUtils.usingStringUtilsClass(input));
}
@Test
void givenString_whenUsingWordUtilsClass_thenCapitalizeFirstCharacter() {
String input = "smile sunshine is good for your teeth";
assertEquals("Smile Sunshine Is Good For Your Teeth", WordUtils.capitalizeFully(input));
}
}

View File

@ -0,0 +1,69 @@
package com.baeldung.strcontainsnumber;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertFalse;
import org.junit.Test;
public class StrContainsNumberUtilsUnitTest {
private static final String INPUT_WITH_NUMBERS = "We hope 2024 will be great";
private static final String INPUT_WITHOUT_NUMBERS = "Hello world";
@Test
public void givenInputString_whenUsingMatchesMethod_ThenCheck() {
assertTrue(StrContainsNumberUtils.checkUsingMatchesMethod(INPUT_WITH_NUMBERS));
assertFalse(StrContainsNumberUtils.checkUsingMatchesMethod(INPUT_WITHOUT_NUMBERS));
assertFalse(StrContainsNumberUtils.checkUsingMatchesMethod(""));
assertFalse(StrContainsNumberUtils.checkUsingMatchesMethod(null));
}
@Test
public void givenInputString_whenUsingPatternClass_ThenCheck() {
assertTrue(StrContainsNumberUtils.checkUsingPatternClass(INPUT_WITH_NUMBERS));
assertFalse(StrContainsNumberUtils.checkUsingPatternClass(INPUT_WITHOUT_NUMBERS));
assertFalse(StrContainsNumberUtils.checkUsingPatternClass(""));
assertFalse(StrContainsNumberUtils.checkUsingPatternClass(null));
}
@Test
public void givenInputString_whenUsingReplaceAllMethod_ThenCheck() {
assertTrue(StrContainsNumberUtils.checkUsingReplaceAllMethod(INPUT_WITH_NUMBERS));
assertFalse(StrContainsNumberUtils.checkUsingReplaceAllMethod(INPUT_WITHOUT_NUMBERS));
assertFalse(StrContainsNumberUtils.checkUsingReplaceAllMethod(""));
assertFalse(StrContainsNumberUtils.checkUsingReplaceAllMethod(null));
}
@Test
public void givenInputString_whenUsingIsDigitMethod_ThenCheck() {
assertTrue(StrContainsNumberUtils.checkUsingIsDigitMethod(INPUT_WITH_NUMBERS));
assertFalse(StrContainsNumberUtils.checkUsingIsDigitMethod(INPUT_WITHOUT_NUMBERS));
assertFalse(StrContainsNumberUtils.checkUsingIsDigitMethod(""));
assertFalse(StrContainsNumberUtils.checkUsingIsDigitMethod(null));
}
@Test
public void givenInputString_whenUsingStreamApi_ThenCheck() {
assertTrue(StrContainsNumberUtils.checkUsingStreamApi(INPUT_WITH_NUMBERS));
assertFalse(StrContainsNumberUtils.checkUsingStreamApi(INPUT_WITHOUT_NUMBERS));
assertFalse(StrContainsNumberUtils.checkUsingStreamApi(""));
assertFalse(StrContainsNumberUtils.checkUsingStreamApi(null));
}
@Test
public void givenInputString_whenUsingApacheCommonsLang_ThenCheck() {
assertTrue(StrContainsNumberUtils.checkUsingApacheCommonsLang(INPUT_WITH_NUMBERS));
assertFalse(StrContainsNumberUtils.checkUsingApacheCommonsLang(INPUT_WITHOUT_NUMBERS));
assertFalse(StrContainsNumberUtils.checkUsingApacheCommonsLang(""));
assertFalse(StrContainsNumberUtils.checkUsingApacheCommonsLang(null));
}
@Test
public void givenInputString_whenUsingGuava_ThenCheck() {
assertTrue(StrContainsNumberUtils.checkUsingGuava(INPUT_WITH_NUMBERS));
assertFalse(StrContainsNumberUtils.checkUsingGuava(INPUT_WITHOUT_NUMBERS));
assertFalse(StrContainsNumberUtils.checkUsingGuava(""));
assertFalse(StrContainsNumberUtils.checkUsingGuava(null));
}
}

View File

@ -73,6 +73,7 @@
<module>core-java-arrays-multidimensional</module>
<module>core-java-arrays-convert</module>
<module>core-java-arrays-operations-basic</module>
<module>core-java-arrays-operations-basic-2</module>
<module>core-java-arrays-operations-advanced</module>
<module>core-java-arrays-operations-advanced-2</module>
<module>core-java-booleans</module>

View File

@ -11,7 +11,7 @@
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-2</relativePath>
<relativePath>../../parent-boot-2</relativePath>
</parent>
<dependencyManagement>

View File

View File

@ -11,7 +11,7 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<artifactId>patterns-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>

View File

@ -12,7 +12,7 @@
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-2</relativePath>
<relativePath>../../parent-boot-2</relativePath>
</parent>
<dependencyManagement>

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