Merge branch 'eugenp:master' into master
This commit is contained in:
+43
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.algorithms.primeundernumber;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class LargestPrimeFinder {
|
||||
|
||||
public static int findByBruteForce(int n) {
|
||||
for (int i = n - 1; i >= 2; i--) {
|
||||
if (isPrime(i)) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1; // Return -1 if no prime number is found
|
||||
}
|
||||
|
||||
public static boolean isPrime(int number) {
|
||||
for (int i = 2; i <= Math.sqrt(number); i++) {
|
||||
if (number % i == 0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static int findBySieveOfEratosthenes(int n) {
|
||||
boolean[] isPrime = new boolean[n];
|
||||
Arrays.fill(isPrime, true);
|
||||
for (int p = 2; p*p < n; p++) {
|
||||
if (isPrime[p]) {
|
||||
for (int i = p * p; i < n; i += p) {
|
||||
isPrime[i] = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = n - 1; i >= 2; i--) {
|
||||
if (isPrime[i]) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.algorithms.primeundernumber;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class LargestPrimeFinderUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenNormalCases_whenFindPrime_ThenFoundResult() {
|
||||
assertEquals(7, LargestPrimeFinder.findByBruteForce(10));
|
||||
assertEquals(97, LargestPrimeFinder.findByBruteForce(100));
|
||||
assertEquals(7, LargestPrimeFinder.findBySieveOfEratosthenes(10));
|
||||
assertEquals(97, LargestPrimeFinder.findBySieveOfEratosthenes(100));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEdgeCases_whenFindPrime_ThenNotFoundResult() {
|
||||
assertEquals(-1, LargestPrimeFinder.findByBruteForce(0));
|
||||
assertEquals(-1, LargestPrimeFinder.findByBruteForce(1));
|
||||
assertEquals(-1, LargestPrimeFinder.findByBruteForce(2));
|
||||
assertEquals(-1, LargestPrimeFinder.findBySieveOfEratosthenes(0));
|
||||
assertEquals(-1, LargestPrimeFinder.findBySieveOfEratosthenes(1));
|
||||
assertEquals(-1, LargestPrimeFinder.findBySieveOfEratosthenes(2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLargeInput_whenFindPrime_ThenFoundResult() {
|
||||
assertEquals(99991, LargestPrimeFinder.findByBruteForce(100000));
|
||||
assertEquals(99991, LargestPrimeFinder.findBySieveOfEratosthenes(100000));
|
||||
}
|
||||
}
|
||||
@@ -13,3 +13,4 @@ This module contains articles about searching algorithms.
|
||||
- [Range Search Algorithm in Java](https://www.baeldung.com/java-range-search)
|
||||
- [Fast Pattern Matching of Strings Using Suffix Tree in Java](https://www.baeldung.com/java-pattern-matching-suffix-tree)
|
||||
- [Find the Kth Smallest Element in Two Sorted Arrays in Java](https://www.baeldung.com/java-kth-smallest-element-in-sorted-arrays)
|
||||
- [Find the First Non-repeating Element of a List](https://www.baeldung.com/java-list-find-first-non-repeating-element)
|
||||
|
||||
@@ -19,10 +19,29 @@
|
||||
<artifactId>validation-api</artifactId>
|
||||
<version>${javax.validation.validation-api.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.camel</groupId>
|
||||
<artifactId>camel-core</artifactId>
|
||||
<version>${camel.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.camel</groupId>
|
||||
<artifactId>camel-test-junit5</artifactId>
|
||||
<version>${camel.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.camel</groupId>
|
||||
<artifactId>camel-main</artifactId>
|
||||
<version>${camel.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<javax.validation.validation-api.version>2.0.1.Final</javax.validation.validation-api.version>
|
||||
<camel.version>4.3.0</camel.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.dynamicrouter;
|
||||
|
||||
import org.apache.camel.ExchangeProperties;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public class DynamicRouterBean {
|
||||
public String route(String body, @ExchangeProperties Map<String, Object> properties) {
|
||||
int invoked = (int) properties.getOrDefault("invoked", 0) + 1;
|
||||
|
||||
properties.put("invoked", invoked);
|
||||
|
||||
if (invoked == 1) {
|
||||
switch (body.toLowerCase()) {
|
||||
case "mock":
|
||||
return "mock:dynamicRouter";
|
||||
case "direct":
|
||||
return "mock:directDynamicRouter";
|
||||
case "seda":
|
||||
return "mock:sedaDynamicRouter";
|
||||
case "file":
|
||||
return "mock:fileDynamicRouter";
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.dynamicrouter;
|
||||
|
||||
import org.apache.camel.builder.RouteBuilder;
|
||||
|
||||
public class DynamicRouterRoute extends RouteBuilder {
|
||||
|
||||
@Override
|
||||
public void configure() {
|
||||
|
||||
from("direct:dynamicRouter").dynamicRouter(method(DynamicRouterBean.class, "route"));
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package dynamicrouter;
|
||||
|
||||
import com.baeldung.dynamicrouter.DynamicRouterRoute;
|
||||
import org.apache.camel.RoutesBuilder;
|
||||
import org.apache.camel.component.mock.MockEndpoint;
|
||||
import org.apache.camel.test.junit5.CamelTestSupport;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class DynamicRouterRouteUnitTest extends CamelTestSupport {
|
||||
|
||||
@Override
|
||||
protected RoutesBuilder createRouteBuilder() {
|
||||
return new DynamicRouterRoute();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenDynamicRouter_whenMockEndpointExpectedMessageCountOneAndMockAsMessageBody_thenMessageSentToDynamicRouter() throws InterruptedException {
|
||||
|
||||
MockEndpoint mockDynamicEndpoint = getMockEndpoint("mock:dynamicRouter");
|
||||
mockDynamicEndpoint.expectedMessageCount(1);
|
||||
|
||||
template.send("direct:dynamicRouter", exchange -> exchange.getIn()
|
||||
.setBody("mock"));
|
||||
MockEndpoint.assertIsSatisfied(context);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenDynamicRouter_whenMockEndpointExpectedMessageCountOneAndDirectAsMessageBody_thenMessageSentToDynamicRouter() throws InterruptedException {
|
||||
|
||||
MockEndpoint mockDynamicEndpoint = context.getEndpoint("mock:directDynamicRouter", MockEndpoint.class);
|
||||
mockDynamicEndpoint.expectedMessageCount(1);
|
||||
|
||||
template.send("direct:dynamicRouter", exchange -> exchange.getIn()
|
||||
.setBody("direct"));
|
||||
|
||||
MockEndpoint.assertIsSatisfied(context);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenDynamicRouter_whenMockEndpointExpectedMessageCountOneAndSedaAsMessageBody_thenMessageSentToDynamicRouter() throws InterruptedException {
|
||||
|
||||
MockEndpoint mockDynamicEndpoint = context.getEndpoint("mock:sedaDynamicRouter", MockEndpoint.class);
|
||||
mockDynamicEndpoint.expectedMessageCount(1);
|
||||
|
||||
template.send("direct:dynamicRouter", exchange -> exchange.getIn()
|
||||
.setBody("seda"));
|
||||
MockEndpoint.assertIsSatisfied(context);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenDynamicRouter_whenMockEndpointExpectedMessageCountOneAndBookAsMessageBody_thenMessageSentToDynamicRouter() throws InterruptedException {
|
||||
|
||||
MockEndpoint mockDynamicEndpoint = getMockEndpoint("mock:fileDynamicRouter");
|
||||
mockDynamicEndpoint.expectedMessageCount(1);
|
||||
|
||||
template.send("direct:dynamicRouter", exchange -> exchange.getIn()
|
||||
.setBody("file"));
|
||||
MockEndpoint.assertIsSatisfied(context);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,2 +1,4 @@
|
||||
## Relevant Articles
|
||||
- [Find the Middle Element of an Array in Java](https://www.baeldung.com/java-array-middle-item)
|
||||
- [Find the Equilibrium Indexes of an Array in Java](https://www.baeldung.com/java-equilibrium-index-array)
|
||||
- [Moves Zeros to the End of an Array in Java](https://www.baeldung.com/java-array-sort-move-zeros-end)
|
||||
|
||||
@@ -7,4 +7,5 @@
|
||||
- [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)
|
||||
- [Collect Stream of entrySet() to a LinkedHashMap](https://www.baeldung.com/java-linkedhashmap-entryset-stream)
|
||||
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-6)
|
||||
|
||||
@@ -8,3 +8,4 @@
|
||||
- [How to Check if All Runnables Are Done](https://www.baeldung.com/java-runnables-check-status)
|
||||
- [Parallelize for Loop in Java](https://www.baeldung.com/java-for-loop-parallel)
|
||||
- [How to Effectively Unit Test CompletableFuture](https://www.baeldung.com/java-completablefuture-unit-test)
|
||||
- [How to Collect All Results and Handle Exceptions With CompletableFuture in a Loop](https://www.baeldung.com/java-completablefuture-collect-results-handle-exceptions)
|
||||
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
package com.baeldung.concurrent.completablefuture;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.stream.Collectors;
|
||||
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;
|
||||
|
||||
public class CombiningCompletableFuturesUnitTest {
|
||||
|
||||
private final Logger logger = mock(Logger.class);
|
||||
|
||||
private static Stream<Arguments> clientData() {
|
||||
return Stream.of(
|
||||
Arguments.of(List.of("Good Resource"), 1, 0),
|
||||
Arguments.of(List.of("Bad Resource"), 0, 1),
|
||||
Arguments.of(List.of("Good Resource", "Bad Resource"), 1, 1),
|
||||
Arguments.of(List.of("Good Resource", "Bad Resource", "Good Resource", "Bad Resource", "Good Resource"), 3, 2)
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("clientData")
|
||||
public void givenMicroserviceClient_whenMultipleCreateResource_thenCombineResults(List<String> inputs, int successCount, int errorCount) {
|
||||
MicroserviceClient mockMicroservice = mock(MicroserviceClient.class);
|
||||
// Return an identifier of 123 on "Good Resource"
|
||||
when(mockMicroservice.createResource("Good Resource"))
|
||||
.thenReturn(CompletableFuture.completedFuture(123L));
|
||||
// Throw an exception on "Bad Resource"
|
||||
when(mockMicroservice.createResource("Bad Resource"))
|
||||
.thenReturn(CompletableFuture.failedFuture(new IllegalArgumentException("Bad Resource")));
|
||||
|
||||
// Given a list of CompletableFutures from our microservice calls...
|
||||
List<CompletableFuture<Long>> clientCalls = new ArrayList<>();
|
||||
for (String resource : inputs) {
|
||||
clientCalls.add(mockMicroservice.createResource(resource));
|
||||
}
|
||||
|
||||
// When all CompletableFutures are completed (exceptionally or otherwise)...
|
||||
Map<Boolean, List<Long>> resultsByValidity = clientCalls.stream()
|
||||
.map(this::handleFuture)
|
||||
.collect(Collectors.partitioningBy(resourceId -> resourceId != -1L));
|
||||
|
||||
// Then the returned resource identifiers should match what is expected...
|
||||
List<Long> validResults = resultsByValidity.getOrDefault(true, List.of());
|
||||
assertThat(validResults.size()).isEqualTo(successCount);
|
||||
|
||||
// And the logger mock should be called once for each exception with the expected error message
|
||||
List<Long> invalidResults = resultsByValidity.getOrDefault(false, List.of());
|
||||
assertThat(invalidResults.size()).isEqualTo(errorCount);
|
||||
verify(logger, times(errorCount))
|
||||
.error(eq("Encountered error: java.lang.IllegalArgumentException: Bad Resource"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Completes the given CompletableFuture, handling any exceptions that are thrown.
|
||||
* @param future the CompletableFuture to complete.
|
||||
* @return the resource identifier (-1 if the request failed).
|
||||
*/
|
||||
private Long handleFuture(CompletableFuture<Long> future) {
|
||||
return future
|
||||
.exceptionally(this::handleError)
|
||||
.join();
|
||||
}
|
||||
|
||||
private Long handleError(Throwable throwable) {
|
||||
logger.error("Encountered error: " + throwable);
|
||||
return -1L;
|
||||
}
|
||||
|
||||
interface MicroserviceClient {
|
||||
CompletableFuture<Long> createResource(String resourceName);
|
||||
}
|
||||
|
||||
interface Logger {
|
||||
void error(String message);
|
||||
}
|
||||
}
|
||||
@@ -4,3 +4,4 @@ This module contains articles about date operations in Java.
|
||||
### Relevant Articles:
|
||||
- [Calculate Number of Weekdays Between Two Dates in Java](https://www.baeldung.com/java-count-weekdays-between-two-dates)
|
||||
- [Convert Long to Date in Java](https://www.baeldung.com/java-long-date-conversion)
|
||||
- [Convert Date to Unix Timestamp in Java](https://www.baeldung.com/java-convert-date-unix-timestamp)
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
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-datetime-conversion-2</artifactId>
|
||||
<version>${project.parent.version}</version>
|
||||
<name>core-java-datetime-conversion-2</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
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-datetime-conversion</artifactId>
|
||||
<version>${project.parent.version}</version>
|
||||
<name>core-java-datetime-conversion</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
package com.baeldung.math.rodcutting;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class RodCuttingProblem {
|
||||
static int maxRevenueG;
|
||||
public static int usingRecursion(int[] prices, int n) {
|
||||
if (n <= 0) {
|
||||
return 0;
|
||||
}
|
||||
int maxRevenue = Integer.MIN_VALUE;
|
||||
|
||||
for (int i = 1; i <= n; i++) {
|
||||
maxRevenue = Math.max(maxRevenue, prices[i - 1] + usingRecursion(prices, n - i));
|
||||
}
|
||||
return maxRevenue;
|
||||
}
|
||||
|
||||
public static int usingMemoizedRecursion(int[] prices, int n) {
|
||||
int[] memo = new int[n + 1];
|
||||
Arrays.fill(memo, -1);
|
||||
|
||||
return memoizedHelper(prices, n, memo);
|
||||
}
|
||||
|
||||
private static int memoizedHelper(int[] prices, int n, int[] memo) {
|
||||
if (n <= 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (memo[n] != -1) {
|
||||
return memo[n];
|
||||
}
|
||||
|
||||
int maxRevenue = Integer.MIN_VALUE;
|
||||
|
||||
for (int i = 1; i <= n; i++) {
|
||||
maxRevenue = Math.max(maxRevenue, prices[i - 1] + memoizedHelper(prices, n - i, memo));
|
||||
}
|
||||
|
||||
memo[n] = maxRevenue;
|
||||
return maxRevenue;
|
||||
}
|
||||
|
||||
public static int usingDynamicProgramming(int[] prices, int n) {
|
||||
int[] dp = new int[n + 1];
|
||||
for (int i = 1; i <= n; i++) {
|
||||
int maxRevenue = Integer.MIN_VALUE;
|
||||
|
||||
for (int j = 1; j <= i; j++) {
|
||||
maxRevenue = Math.max(maxRevenue, prices[j - 1] + dp[i - j]);
|
||||
}
|
||||
dp[i] = maxRevenue;
|
||||
}
|
||||
return dp[n];
|
||||
}
|
||||
|
||||
public static int usingUnboundedKnapsack(int[] prices, int n) {
|
||||
int[] dp = new int[n + 1];
|
||||
|
||||
for (int i = 1; i <= n; i++) {
|
||||
for (int j = 0; j < prices.length; j++) {
|
||||
if (j + 1 <= i) {
|
||||
dp[i] = Math.max(dp[i], dp[i - (j + 1)] + prices[j]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return dp[n];
|
||||
}
|
||||
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.math.rodcutting;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class RodCuttingProblemUnitTest {
|
||||
@Test
|
||||
void givenARod_whenUsingRecursion_thenFindMaxRevenue() {
|
||||
int[] prices = {1, 5, 8, 9};
|
||||
int rodLength = 4;
|
||||
int maxRevenue = RodCuttingProblem.usingRecursion(prices, rodLength);
|
||||
assertEquals(10, maxRevenue);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenARod_whenUsingMemoizedRecursion_thenFindMaxRevenue() {
|
||||
int[] prices = {1, 5, 8, 9};
|
||||
int rodLength = 4;
|
||||
int maxRevenue = RodCuttingProblem.usingMemoizedRecursion(prices, rodLength);
|
||||
assertEquals(10, maxRevenue);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenARod_whenUsingDynamicProgramming_thenFindMaxRevenue() {
|
||||
int[] prices = {1, 5, 8, 9};
|
||||
int rodLength = 4;
|
||||
int maxRevenue = RodCuttingProblem.usingDynamicProgramming(prices, rodLength);
|
||||
assertEquals(10, maxRevenue);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenARod_whenUsingGreedy_thenFindMaxRevenue() {
|
||||
int[] prices = {1, 5, 8, 9};
|
||||
int rodLength = 4;
|
||||
int maxRevenue = RodCuttingProblem.usingUnboundedKnapsack(prices, rodLength);
|
||||
assertEquals(10, maxRevenue);
|
||||
}
|
||||
}
|
||||
@@ -11,3 +11,4 @@ This module contains articles about Object-oriented programming (OOP) patterns i
|
||||
- [Should We Create an Interface for Only One Implementation?](https://www.baeldung.com/java-interface-single-implementation)
|
||||
- [How to Deep Copy an ArrayList in Java](https://www.baeldung.com/java-arraylist-deep-copy)
|
||||
- [Stateless Object in Java](https://www.baeldung.com/java-stateless-object)
|
||||
- [Mutable vs. Immutable Objects in Java](https://www.baeldung.com/java-mutable-vs-immutable-objects)
|
||||
|
||||
@@ -11,3 +11,4 @@ This module contains articles about Java operators
|
||||
- [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)
|
||||
- [Convert Infix to Postfix Expressions in Java](https://www.baeldung.com/java-convert-infix-to-postfix-expressions)
|
||||
|
||||
@@ -6,3 +6,5 @@
|
||||
- [URL Query Manipulation in Java](https://www.baeldung.com/java-url-query-manipulation)
|
||||
- [Understanding the java.net.SocketException Broken Pipe Error](https://www.baeldung.com/java-socketexception-broken-pipe-error)
|
||||
- [Normalize a URL in Java](https://www.baeldung.com/java-url-normalization)
|
||||
- [Translating Space Characters in URLEncoder](https://www.baeldung.com/java-urlencoder-translate-space-characters)
|
||||
- [Creating a Custom URL Connection](https://www.baeldung.com/java-custom-url-connection)
|
||||
|
||||
@@ -31,11 +31,6 @@
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-core</artifactId>
|
||||
<version>${spring.core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-core</artifactId>
|
||||
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.streams.range;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class StreamRangeUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenRangeStreamUsingLimitSkip_thenPrintsRange() {
|
||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
|
||||
List<Integer> expectedRange = Arrays.asList(3, 4, 5, 6, 7);
|
||||
|
||||
List<Integer> range = numbers.stream()
|
||||
.skip(2)
|
||||
.limit(5)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertEquals(expectedRange, range);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRangeStreamUsingCollectingAndThen_thenPrintsRange() {
|
||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
|
||||
List<Integer> expectedRange = Arrays.asList(3, 4, 5, 6, 7);
|
||||
|
||||
List<Integer> range = numbers.stream()
|
||||
.filter(n -> n >= 3 && n <= 7)
|
||||
.collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));
|
||||
|
||||
assertEquals(expectedRange, range);
|
||||
}
|
||||
}
|
||||
@@ -15,3 +15,4 @@
|
||||
- [Simple Morse Code Translation in Java](https://www.baeldung.com/java-morse-code-english-translate)
|
||||
- [How to Determine if a String Contains Invalid Encoded Characters](https://www.baeldung.com/java-check-string-contains-invalid-encoded-characters)
|
||||
- [Regular Expression for Password Validation in Java](https://www.baeldung.com/java-regex-password-validation)
|
||||
- [Mask an Email Address and Phone Number in Java](https://www.baeldung.com/java-mask-email-address-phone-number)
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
|
||||
### Relevant Articles:
|
||||
### Relevant Articles:
|
||||
- [Count Uppercase and Lowercase Letters in a String](https://www.baeldung.com/java-string-count-letters-uppercase-lowercase)
|
||||
|
||||
@@ -1,72 +1,34 @@
|
||||
<?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-string-operations-8</artifactId>
|
||||
<name>core-java-string-operations-8</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.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${apache.commons.lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-text</artifactId>
|
||||
<version>${commons-text.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.liquibase</groupId>
|
||||
<artifactId>liquibase-core</artifactId>
|
||||
<version>4.9.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>5.8.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.liquibase</groupId>
|
||||
<artifactId>liquibase-core</artifactId>
|
||||
<version>4.9.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.13.2</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>${maven.compiler.source}</source>
|
||||
<target>${maven.compiler.target}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>11</maven.compiler.source>
|
||||
<maven.compiler.target>11</maven.compiler.target>
|
||||
<apache.commons.lang3.version>3.13.0</apache.commons.lang3.version>
|
||||
<commons-text.version>1.10.0</commons-text.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
<?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-string-operations-8</artifactId>
|
||||
<name>core-java-string-operations-8</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>${maven.compiler.source}</source>
|
||||
<target>${maven.compiler.target}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>11</maven.compiler.source>
|
||||
<maven.compiler.target>11</maven.compiler.target>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package com.baeldung.checkifstringisbased64;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Base64;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
public class CheckIfStringIsBased64UnitTest {
|
||||
|
||||
@Test
|
||||
public void givenBase64EncodedString_whenDecoding_thenNoException() {
|
||||
try {
|
||||
Base64.getDecoder().decode("SGVsbG8gd29ybGQ=");
|
||||
assertTrue(true);
|
||||
} catch (IllegalArgumentException e) {
|
||||
fail("Unexpected exception: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNonBase64String_whenDecoding_thenCatchException() {
|
||||
try {
|
||||
Base64.getDecoder().decode("Hello world!");
|
||||
fail("Expected IllegalArgumentException was not thrown");
|
||||
} catch (IllegalArgumentException e) {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenOperatingRegex_thenCheckIfItIsBase64Encoded() {
|
||||
Pattern BASE64_PATTERN = Pattern.compile(
|
||||
"^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$"
|
||||
);
|
||||
|
||||
assertTrue(BASE64_PATTERN.matcher("SGVsbG8gd29ybGQ=").matches());
|
||||
}
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
package com.baeldung.countupperandlowercasechars;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class CountUpperAndLowercaseCharsUnitTest {
|
||||
private static final String MY_STRING = "Hi, Welcome to Baeldung! Let's count letters!";
|
||||
|
||||
@Test
|
||||
void whenUsingCountByCharacterRange_thenGetExpectedResult() {
|
||||
LetterCount result = LetterCount.countByCharacterRange(MY_STRING);
|
||||
assertEquals(4, result.getUppercaseCount());
|
||||
assertEquals(31, result.getLowercaseCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingCountByCharacterIsLowerOrUpperCase_thenGetExpectedResult() {
|
||||
LetterCount result = LetterCount.countByCharacterIsUpperLower(MY_STRING);
|
||||
assertEquals(4, result.getUppercaseCount());
|
||||
assertEquals(31, result.getLowercaseCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingCountByStreamApi_thenGetExpectedResult() {
|
||||
LetterCount result = LetterCount.countByStreamAPI(MY_STRING);
|
||||
assertEquals(4, result.getUppercaseCount());
|
||||
assertEquals(31, result.getLowercaseCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingIsUpperCaseAndIsLowerCase_thenUnicodeCharactersCanBeChecked() {
|
||||
assertTrue(Character.isLowerCase('ä'));
|
||||
assertTrue(Character.isUpperCase('Ä'));
|
||||
}
|
||||
}
|
||||
|
||||
class LetterCount {
|
||||
private int uppercaseCount;
|
||||
private int lowercaseCount;
|
||||
|
||||
private LetterCount(int uppercaseCount, int lowercaseCount) {
|
||||
this.uppercaseCount = uppercaseCount;
|
||||
this.lowercaseCount = lowercaseCount;
|
||||
}
|
||||
|
||||
public static LetterCount countByCharacterRange(String input) {
|
||||
int upperCount = 0;
|
||||
int lowerCount = 0;
|
||||
for (char c : input.toCharArray()) {
|
||||
if (c >= 'A' && c <= 'Z') {
|
||||
upperCount++;
|
||||
}
|
||||
if (c >= 'a' && c <= 'z') {
|
||||
lowerCount++;
|
||||
}
|
||||
}
|
||||
return new LetterCount(upperCount, lowerCount);
|
||||
}
|
||||
|
||||
public static LetterCount countByCharacterIsUpperLower(String input) {
|
||||
int upperCount = 0;
|
||||
int lowerCount = 0;
|
||||
for (char c : input.toCharArray()) {
|
||||
if (Character.isUpperCase(c)) {
|
||||
upperCount++;
|
||||
}
|
||||
if (Character.isLowerCase(c)) {
|
||||
lowerCount++;
|
||||
}
|
||||
}
|
||||
return new LetterCount(upperCount, lowerCount);
|
||||
}
|
||||
|
||||
public static LetterCount countByStreamAPI(String input) {
|
||||
return new LetterCount(
|
||||
(int) input.chars().filter(Character::isUpperCase).count(),
|
||||
(int) input.chars().filter(Character::isLowerCase).count()
|
||||
);
|
||||
}
|
||||
|
||||
public int getUppercaseCount() {
|
||||
return uppercaseCount;
|
||||
}
|
||||
|
||||
public int getLowercaseCount() {
|
||||
return lowercaseCount;
|
||||
}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package com.baeldung.findlargestnuminstring;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class FindLargestNumInStringUnitTest {
|
||||
String inputString = "The numbers are 10, 20, and 5";
|
||||
int expectedLargestNumber = 20;
|
||||
|
||||
@Test
|
||||
public void givenInputString_whenUsingBasicApproach_thenFindingLargestNumber() {
|
||||
String[] numbers = inputString.split("[^0-9]+");
|
||||
|
||||
int largestNumber = Integer.MIN_VALUE;
|
||||
for (String number : numbers) {
|
||||
if (!number.isEmpty()) {
|
||||
int currentNumber = Integer.parseInt(number);
|
||||
if (currentNumber > largestNumber) {
|
||||
largestNumber = currentNumber;
|
||||
}
|
||||
}
|
||||
}
|
||||
assertEquals(expectedLargestNumber, largestNumber);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInputString_whenUsingRegularExpression_thenFindingLargestNumber() {
|
||||
Pattern pattern = Pattern.compile("\\d+");
|
||||
Matcher matcher = pattern.matcher(inputString);
|
||||
|
||||
int largestNumber = Integer.MIN_VALUE;
|
||||
while (matcher.find()) {
|
||||
int currentNumber = Integer.parseInt(matcher.group());
|
||||
if (currentNumber > largestNumber) {
|
||||
largestNumber = currentNumber;
|
||||
}
|
||||
}
|
||||
assertEquals(expectedLargestNumber, largestNumber);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInputString_whenUsingStreamAndLambdaExpression_thenFindingLargestNumber() {
|
||||
int largestNumber = Arrays.stream(inputString.split("[^0-9]+"))
|
||||
.filter(s -> !s.isEmpty())
|
||||
.mapToInt(Integer::parseInt)
|
||||
.max()
|
||||
.orElse(Integer.MIN_VALUE);
|
||||
|
||||
assertEquals(expectedLargestNumber, largestNumber);
|
||||
|
||||
}
|
||||
}
|
||||
@@ -18,18 +18,17 @@
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.jr</groupId>
|
||||
<artifactId>jackson-jr-all</artifactId>
|
||||
<version>2.15.2</version>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.jr</groupId>
|
||||
<artifactId>jackson-jr-annotation-support</artifactId>
|
||||
<version>2.15.2</version>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>RELEASE</version>
|
||||
<scope>compile</scope>
|
||||
<version>${lombok.version}</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
@@ -44,4 +43,8 @@
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<jackson.version>2.16.0</jackson.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -112,12 +112,6 @@
|
||||
<artifactId>commons-io</artifactId>
|
||||
<version>2.11.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>RELEASE</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.annotation</groupId>
|
||||
<artifactId>javax.annotation-api</artifactId>
|
||||
|
||||
@@ -6,3 +6,4 @@ This module contains articles about JSON Conversions
|
||||
- [Convert JSON Array to Java List](https://www.baeldung.com/java-convert-json-array-to-list)
|
||||
- [Reading JSON Documents as Maps and Comparing Them](https://www.baeldung.com/java-json-maps-comparison)
|
||||
- [Convert Byte Array to JSON and Vice Versa in Java](https://www.baeldung.com/java-json-byte-array-conversion)
|
||||
- [Preventing Gson from Expressing Integers as Floats](https://www.baeldung.com/java-gson-prevent-expressing-integers-as-floats)
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user