Merge branch 'eugenp:master' into master
This commit is contained in:
commit
f682eba397
@ -14,16 +14,6 @@
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-math3</artifactId>
|
||||
<version>${commons-math3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-codec</groupId>
|
||||
<artifactId>commons-codec</artifactId>
|
||||
<version>${commons-codec.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
|
@ -1,7 +1,5 @@
|
||||
package com.baeldung.algorithms;
|
||||
|
||||
|
||||
|
||||
import com.baeldung.algorithms.ga.dijkstra.Dijkstra;
|
||||
import com.baeldung.algorithms.ga.dijkstra.Graph;
|
||||
import com.baeldung.algorithms.ga.dijkstra.Node;
|
||||
|
@ -6,4 +6,5 @@
|
||||
- [Calculate Distance Between Two Coordinates in Java](https://www.baeldung.com/java-find-distance-between-points)
|
||||
- [Rotate Arrays in Java](https://www.baeldung.com/java-rotate-arrays)
|
||||
- [Find Missing Number From a Given Array in Java](https://www.baeldung.com/java-array-find-missing-number)
|
||||
- [Calculate Weighted Mean in Java](https://www.baeldung.com/java-compute-weighted-average)
|
||||
- More articles: [[<-- prev]](/algorithms-miscellaneous-6)
|
||||
|
@ -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;
|
||||
}
|
||||
}
|
@ -0,0 +1,123 @@
|
||||
package com.baeldung.algorithms.stringrotation;
|
||||
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Queue;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class StringRotation {
|
||||
|
||||
public static boolean doubledOriginContainsRotation(String origin, String rotation) {
|
||||
if (origin.length() == rotation.length()) {
|
||||
return origin.concat(origin)
|
||||
.contains(rotation);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public static boolean isRotationUsingCommonStartWithOrigin(String origin, String rotation) {
|
||||
|
||||
if (origin.length() == rotation.length()) {
|
||||
|
||||
List<Integer> indexes = IntStream.range(0, origin.length())
|
||||
.filter(i -> rotation.charAt(i) == origin.charAt(0))
|
||||
.boxed()
|
||||
.collect(Collectors.toList());
|
||||
|
||||
for (int startingAt : indexes) {
|
||||
if (isRotation(startingAt, rotation, origin)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
static boolean isRotation(int startingAt, String rotation, String origin) {
|
||||
|
||||
for (int i = 0; i < origin.length(); i++) {
|
||||
if (rotation.charAt((startingAt + i) % origin.length()) != origin.charAt(i)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public static boolean isRotationUsingQueue(String origin, String rotation) {
|
||||
|
||||
if (origin.length() == rotation.length()) {
|
||||
return checkWithQueue(origin, rotation);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
static boolean checkWithQueue(String origin, String rotation) {
|
||||
|
||||
if (origin.length() == rotation.length()) {
|
||||
|
||||
Queue<Character> originQueue = getCharactersQueue(origin);
|
||||
|
||||
Queue<Character> rotationQueue = getCharactersQueue(rotation);
|
||||
|
||||
int k = rotation.length();
|
||||
while (k > 0 && null != rotationQueue.peek()) {
|
||||
k--;
|
||||
char ch = rotationQueue.peek();
|
||||
rotationQueue.remove();
|
||||
rotationQueue.add(ch);
|
||||
if (rotationQueue.equals(originQueue)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
static Queue<Character> getCharactersQueue(String origin) {
|
||||
return origin.chars()
|
||||
.mapToObj(c -> (char) c)
|
||||
.collect(Collectors.toCollection(LinkedList::new));
|
||||
}
|
||||
|
||||
public static boolean isRotationUsingSuffixAndPrefix(String origin, String rotation) {
|
||||
|
||||
if (origin.length() == rotation.length()) {
|
||||
return checkPrefixAndSuffix(origin, rotation);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
static boolean checkPrefixAndSuffix(String origin, String rotation) {
|
||||
if (origin.length() == rotation.length()) {
|
||||
|
||||
for (int i = 0; i < origin.length(); i++) {
|
||||
if (origin.charAt(i) == rotation.charAt(0)) {
|
||||
if (checkRotationPrefixWithOriginSuffix(origin, rotation, i)) {
|
||||
if (checkOriginPrefixWithRotationSuffix(origin, rotation, i))
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean checkRotationPrefixWithOriginSuffix(String origin, String rotation, int i) {
|
||||
return origin.substring(i)
|
||||
.equals(rotation.substring(0, origin.length() - i));
|
||||
}
|
||||
|
||||
private static boolean checkOriginPrefixWithRotationSuffix(String origin, String rotation, int i) {
|
||||
return origin.substring(0, i)
|
||||
.equals(rotation.substring(origin.length() - i));
|
||||
}
|
||||
}
|
@ -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));
|
||||
}
|
||||
}
|
@ -0,0 +1,61 @@
|
||||
package com.baeldung.algorithms.stringrotation;
|
||||
|
||||
import static com.baeldung.algorithms.stringrotation.StringRotation.doubledOriginContainsRotation;
|
||||
import static com.baeldung.algorithms.stringrotation.StringRotation.isRotationUsingCommonStartWithOrigin;
|
||||
import static com.baeldung.algorithms.stringrotation.StringRotation.isRotationUsingQueue;
|
||||
import static com.baeldung.algorithms.stringrotation.StringRotation.isRotationUsingSuffixAndPrefix;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class StringRotationUnitTest {
|
||||
|
||||
@Test
|
||||
void givenOriginAndRotationInput_whenCheckIfOriginContainsRotation_thenIsRotation() {
|
||||
assertTrue(doubledOriginContainsRotation("abcd", "cdab"));
|
||||
assertTrue(doubledOriginContainsRotation("abcd", "abcd"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenOriginAndRotationInput_whenCheckIfOriginContainsRotation_thenNoRotation() {
|
||||
assertFalse(doubledOriginContainsRotation("abcd", "bbbb"));
|
||||
assertFalse(doubledOriginContainsRotation("abcd", "abcde"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenOriginAndRotationInput_whenCheckingCommonStartWithOrigin_thenIsRotation() {
|
||||
assertTrue(isRotationUsingCommonStartWithOrigin("abcd", "cdab"));
|
||||
assertTrue(isRotationUsingCommonStartWithOrigin("abcd", "abcd"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenOriginAndRotationInput_whenCheckingCommonStartWithOrigin_thenNoRotation() {
|
||||
assertFalse(isRotationUsingCommonStartWithOrigin("abcd", "bbbb"));
|
||||
assertFalse(isRotationUsingCommonStartWithOrigin("abcd", "abcde"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenOriginAndRotationInput_whenCheckingUsingQueues_thenIsRotation() {
|
||||
assertTrue(isRotationUsingQueue("abcd", "cdab"));
|
||||
assertTrue(isRotationUsingQueue("abcd", "abcd"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenOriginAndRotationInput_whenCheckingUsingQueues_thenNoRotation() {
|
||||
assertFalse(isRotationUsingQueue("abcd", "bbbb"));
|
||||
assertFalse(isRotationUsingQueue("abcd", "abcde"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenOriginAndRotationInput_whenCheckingUsingSuffixAndPrefix_thenIsRotation() {
|
||||
assertTrue(isRotationUsingSuffixAndPrefix("abcd", "cdab"));
|
||||
assertTrue(isRotationUsingSuffixAndPrefix("abcd", "abcd"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenOriginAndRotationInput_whenCheckingUsingSuffixAndPrefix_thenNoRotation() {
|
||||
assertFalse(isRotationUsingSuffixAndPrefix("abcd", "bbbb"));
|
||||
assertFalse(isRotationUsingSuffixAndPrefix("abcd", "abcde"));
|
||||
}
|
||||
}
|
@ -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)
|
||||
|
@ -0,0 +1,61 @@
|
||||
package com.baeldung.algorithms.firstnonrepeating;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class FirstNonRepeatingElement {
|
||||
public static Integer findFirstNonRepeatingUsingForLoop(List<Integer> list) {
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
int current = list.get(i);
|
||||
boolean isRepeating = false;
|
||||
for (int j = 0; j < list.size(); j++) {
|
||||
if (i != j && current == list.get(j)) {
|
||||
isRepeating = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!isRepeating) {
|
||||
return current;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static Integer findFirstNonRepeatedElementUsingIndex(List<Integer> list) {
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
if (list.indexOf(list.get(i)) == list.lastIndexOf(list.get(i))) {
|
||||
return list.get(i);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static Integer findFirstNonRepeatingUsingHashMap(List<Integer> list) {
|
||||
Map<Integer, Integer> counts = new HashMap<>();
|
||||
for (int num : list) {
|
||||
counts.put(num, counts.getOrDefault(num, 0) + 1);
|
||||
}
|
||||
for (int num : list) {
|
||||
if (counts.get(num) == 1) {
|
||||
return num;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static Integer findFirstNonRepeatingUsingArray(List<Integer> list) {
|
||||
int maxElement = Collections.max(list);
|
||||
int[] frequency = new int[maxElement + 1];
|
||||
for (int num : list) {
|
||||
frequency[num]++;
|
||||
}
|
||||
for (int num : list) {
|
||||
if (frequency[num] == 1) {
|
||||
return num;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
@ -0,0 +1,43 @@
|
||||
package com.baeldung.algorithms.firstnonrepeating;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class FirstNonRepeatingElementUnitTest {
|
||||
|
||||
private List<Integer> list;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
list = Arrays.asList(1, 2, 3, 2, 1, 4, 5, 4);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingForLoop_thenReturnFirstNonRepeatingElement() {
|
||||
int result = FirstNonRepeatingElement.findFirstNonRepeatingUsingForLoop(list);
|
||||
assertEquals(3, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingIndexOf_thenReturnFirstNonRepeatingElement() {
|
||||
int result = FirstNonRepeatingElement.findFirstNonRepeatedElementUsingIndex(list);
|
||||
assertEquals(3, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingHashMap_thenReturnFirstNonRepeatingElement() {
|
||||
int result = FirstNonRepeatingElement.findFirstNonRepeatingUsingHashMap(list);
|
||||
assertEquals(3, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingArray_thenReturnFirstNonRepeatingElement() {
|
||||
int result = FirstNonRepeatingElement.findFirstNonRepeatingUsingArray(list);
|
||||
assertEquals(3, result);
|
||||
}
|
||||
}
|
@ -20,8 +20,4 @@
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<cxf.version>4.0.0</cxf.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -48,7 +48,6 @@
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<cxf.version>4.0.0</cxf.version>
|
||||
<jakarta-xml.version>4.0.0</jakarta-xml.version>
|
||||
<jakarta.jws.version>3.0.0</jakarta.jws.version>
|
||||
</properties>
|
||||
|
@ -16,12 +16,12 @@
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
|
||||
<version>4.0.0</version>
|
||||
<version>${cxf.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-transports-http-jetty</artifactId>
|
||||
<version>4.0.0</version>
|
||||
<version>${cxf.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>jakarta.xml.ws</groupId>
|
||||
|
@ -115,6 +115,7 @@
|
||||
</profiles>
|
||||
|
||||
<properties>
|
||||
<cxf.version>3.1.8</cxf.version>
|
||||
<spring.version>5.3.25</spring.version>
|
||||
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
|
||||
<jstl.version>1.2</jstl.version>
|
||||
|
@ -35,7 +35,7 @@
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<cxf.version>3.1.8</cxf.version>
|
||||
<cxf.version>4.0.0</cxf.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -16,12 +16,12 @@
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-rs-client</artifactId>
|
||||
<version>${cxf-version}</version>
|
||||
<version>${cxf.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-rs-sse</artifactId>
|
||||
<version>${cxf-version}</version>
|
||||
<version>${cxf.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>jakarta.ws.rs</groupId>
|
||||
@ -60,7 +60,6 @@
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<cxf-version>4.0.0</cxf-version>
|
||||
<jakarta-ws.version>3.1.0</jakarta-ws.version>
|
||||
</properties>
|
||||
|
||||
|
@ -1,2 +1,3 @@
|
||||
## Relevant Articles
|
||||
- [Understanding XSLT Processing in Java](https://www.baeldung.com/java-extensible-stylesheet-language-transformations)
|
||||
- [Add Camel Route at Runtime in Java](https://www.baeldung.com/java-camel-dynamic-route)
|
||||
|
@ -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"));
|
||||
|
||||
}
|
||||
}
|
@ -10,4 +10,6 @@
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
|
||||
<logger name="org.apache.camel.impl.engine" level="WARN"/>
|
||||
</configuration>
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
15
apache-libraries-2/src/test/resources/logback-test.xml
Normal file
15
apache-libraries-2/src/test/resources/logback-test.xml
Normal file
@ -0,0 +1,15 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
|
||||
<logger name="ch.qos.logback.classic.joran.action" level="WARN"/>
|
||||
</configuration>
|
@ -14,4 +14,4 @@ This module contains articles about Apache POI.
|
||||
- [Set the Date Format Using Apache POI](https://www.baeldung.com/java-apache-poi-date-format)
|
||||
- [Replacing Variables in a Document Template with Java](https://www.baeldung.com/java-replace-pattern-word-document-doc-docx)
|
||||
- [Lock Header Rows With Apache POI](https://www.baeldung.com/java-apache-poi-lock-header-rows)
|
||||
- More articles: [[<-- prev]](../apache-poi)
|
||||
- More articles: [[<-- prev]](../apache-poi)[[next -->]](../apache-poi-3)
|
||||
|
@ -27,7 +27,7 @@
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<poi.version>5.2.3</poi.version>
|
||||
<poi.version>5.2.5</poi.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -1,4 +1,10 @@
|
||||
## Relevant Articles
|
||||
## Apache POI
|
||||
|
||||
This module contains articles about Apache POI.
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- [How To Convert Excel Data Into List Of Java Objects](https://www.baeldung.com/java-convert-excel-data-into-list)
|
||||
- [Expand Columns with Apache POI](https://www.baeldung.com/java-apache-poi-expand-columns)
|
||||
- [Apply Bold Text Style for an Entire Row Using Apache POI](https://www.baeldung.com/appache-poi-apply-bold-text-style-entire-row)
|
||||
- More articles: [[<-- prev]](../apache-poi-2)
|
@ -24,50 +24,41 @@
|
||||
<artifactId>poi-scratchpad</artifactId>
|
||||
<version>${poi.version}</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/com.github.ozlerhakan/poiji -->
|
||||
<dependency>
|
||||
<groupId>com.github.ozlerhakan</groupId>
|
||||
<artifactId>poiji</artifactId>
|
||||
<version>${poiji.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi/5.2.3 -->
|
||||
<dependency>
|
||||
<groupId>org.apache.poi</groupId>
|
||||
<artifactId>poi</artifactId>
|
||||
<version>${poi.version}</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas/4.1.2 -->
|
||||
<dependency>
|
||||
<groupId>org.apache.poi</groupId>
|
||||
<artifactId>poi-ooxml-schemas</artifactId>
|
||||
<version>4.1.2</version>
|
||||
<version>${poi-ooxml-schemas.version}</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.xmlbeans/xmlbeans/5.1.1 -->
|
||||
<dependency>
|
||||
<groupId>org.apache.xmlbeans</groupId>
|
||||
<artifactId>xmlbeans</artifactId>
|
||||
<version>5.1.1</version>
|
||||
<version>${xmlbeans.version}</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>4.4</version>
|
||||
<version>${commons-collections4.version}</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.dhatim/fastexcel/0.15.7 -->
|
||||
<dependency>
|
||||
<groupId>org.dhatim</groupId>
|
||||
<artifactId>fastexcel</artifactId>
|
||||
<version>${fastexcel.version}</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.dhatim/fastexcel-reader/0.15.7 -->
|
||||
<dependency>
|
||||
<groupId>org.dhatim</groupId>
|
||||
<artifactId>fastexcel-reader</artifactId>
|
||||
<version>${fastexcel.version}</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/net.sourceforge.jexcelapi/jxl/2.6.12 -->
|
||||
<dependency>
|
||||
<groupId>net.sourceforge.jexcelapi</groupId>
|
||||
<artifactId>jxl</artifactId>
|
||||
@ -77,8 +68,11 @@
|
||||
|
||||
<properties>
|
||||
<poi.version>5.2.5</poi.version>
|
||||
<poiji.version>4.1.1</poiji.version>
|
||||
<fastexcel.version>0.15.7</fastexcel.version>
|
||||
<poi-ooxml-schemas.version>4.1.2</poi-ooxml-schemas.version>
|
||||
<poiji.version>4.2.0</poiji.version>
|
||||
<xmlbeans.version>5.2.0</xmlbeans.version>
|
||||
<commons-collections4.version>4.4</commons-collections4.version>
|
||||
<fastexcel.version>0.17.0</fastexcel.version>
|
||||
<jxl.version>2.6.12</jxl.version>
|
||||
</properties>
|
||||
|
||||
|
@ -60,10 +60,10 @@
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<poi.version>5.2.0</poi.version>
|
||||
<jexcel.version>1.0.6</jexcel.version>
|
||||
<fastexcel.version>0.15.3</fastexcel.version>
|
||||
<maven.resources.plugin.version>3.2.0</maven.resources.plugin.version>
|
||||
<poi.version>5.2.5</poi.version>
|
||||
<jexcel.version>1.0.9</jexcel.version>
|
||||
<fastexcel.version>0.17.0</fastexcel.version>
|
||||
<maven.resources.plugin.version>3.3.1</maven.resources.plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -97,7 +97,7 @@
|
||||
<json-simple.version>1.1.1</json-simple.version>
|
||||
<aws-lambda-java-events.version>3.11.0</aws-lambda-java-events.version>
|
||||
<aws-lambda-java-core.version>1.2.1</aws-lambda-java-core.version>
|
||||
<gson.version>2.8.2</gson.version>
|
||||
<gson.version>2.10.1</gson.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -31,15 +31,21 @@
|
||||
<version>${jackson-databind.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<groupId>org.hibernate.orm</groupId>
|
||||
<artifactId>hibernate-core</artifactId>
|
||||
<version>${hibernate.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<groupId>org.hibernate.orm</groupId>
|
||||
<artifactId>hibernate-hikaricp</artifactId>
|
||||
<version>${hibernate.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.zaxxer</groupId>
|
||||
<artifactId>HikariCP</artifactId>
|
||||
<version>${hikari.cp.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.postgresql</groupId>
|
||||
<artifactId>postgresql</artifactId>
|
||||
@ -70,11 +76,12 @@
|
||||
<properties>
|
||||
<maven.compiler.source>11</maven.compiler.source>
|
||||
<maven.compiler.target>11</maven.compiler.target>
|
||||
<hibernate.version>5.4.21.Final</hibernate.version>
|
||||
<hibernate.version>6.4.2.Final</hibernate.version>
|
||||
<aws-lambda-java-core.version>1.2.0</aws-lambda-java-core.version>
|
||||
<aws-lambda-java-events.version>3.1.0</aws-lambda-java-events.version>
|
||||
<jackson-databind.version>2.11.2</jackson-databind.version>
|
||||
<postgresql.version>42.2.16</postgresql.version>
|
||||
<hikari.cp.version>5.1.0</hikari.cp.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -83,7 +83,7 @@ private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
|
||||
}
|
||||
|
||||
private static SessionFactory createSessionFactory() {
|
||||
Map<String, String> settings = new HashMap<>();
|
||||
Map<String, Object> settings = new HashMap<>();
|
||||
settings.put(URL, System.getenv("DB_URL"));
|
||||
settings.put(DIALECT, "org.hibernate.dialect.PostgreSQLDialect");
|
||||
settings.put(DEFAULT_SCHEMA, "shipping");
|
||||
|
@ -1,7 +1,7 @@
|
||||
package com.baeldung.lambda.shipping;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Embeddable;
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Embeddable;
|
||||
|
||||
@Embeddable
|
||||
public class Checkin {
|
||||
|
@ -1,10 +1,10 @@
|
||||
package com.baeldung.lambda.shipping;
|
||||
|
||||
import javax.persistence.*;
|
||||
import jakarta.persistence.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static javax.persistence.FetchType.EAGER;
|
||||
import static jakarta.persistence.FetchType.EAGER;
|
||||
|
||||
@Entity(name = "consignment")
|
||||
@Table(name = "consignment")
|
||||
|
@ -1,7 +1,7 @@
|
||||
package com.baeldung.lambda.shipping;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Embeddable;
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Embeddable;
|
||||
|
||||
@Embeddable
|
||||
public class Item {
|
||||
|
@ -157,7 +157,7 @@
|
||||
<properties>
|
||||
<groovy-wslite.version>1.1.3</groovy-wslite.version>
|
||||
<assembly.plugin.version>3.4.2</assembly.plugin.version>
|
||||
<compiler.plugin.version>3.8.1</compiler.plugin.version>
|
||||
<compiler.plugin.version>3.12.1</compiler.plugin.version>
|
||||
<groovy.compiler.version>3.9.0</groovy.compiler.version>
|
||||
<groovy-eclipse-batch.version>3.0.9-03</groovy-eclipse-batch.version>
|
||||
</properties>
|
||||
|
@ -1,61 +1,71 @@
|
||||
package com.baeldung.io
|
||||
|
||||
import org.junit.Test
|
||||
|
||||
import groovy.io.FileType
|
||||
import groovy.io.FileVisitResult
|
||||
import org.junit.Test
|
||||
|
||||
import static org.junit.Assert.assertTrue
|
||||
|
||||
class TraverseFileTreeUnitTest {
|
||||
@Test
|
||||
void whenUsingEachFile_filesAreListed() {
|
||||
var files = []
|
||||
new File('src/main/resources').eachFile { file ->
|
||||
println file.name
|
||||
files.add(file.name)
|
||||
}
|
||||
assertTrue(files.size() > 1)
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException)
|
||||
void whenUsingEachFileOnAFile_anErrorOccurs() {
|
||||
var files = []
|
||||
new File('src/main/resources/ioInput.txt').eachFile { file ->
|
||||
println file.name
|
||||
files.add(file.name)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingEachFileMatch_filesAreListed() {
|
||||
var files = []
|
||||
new File('src/main/resources').eachFileMatch(~/io.*\.txt/) { file ->
|
||||
println file.name
|
||||
files.add(file.name)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void whenUsingEachFileRecurse_thenFilesInSubfoldersAreListed() {
|
||||
var files = []
|
||||
new File('src/main').eachFileRecurse(FileType.FILES) { file ->
|
||||
println "$file.parent $file.name"
|
||||
files.add("$file.parent $file.name")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void whenUsingEachFileRecurse_thenDirsInSubfoldersAreListed() {
|
||||
var files = []
|
||||
new File('src/main').eachFileRecurse(FileType.DIRECTORIES) { file ->
|
||||
println "$file.parent $file.name"
|
||||
files.add("$file.parent $file.name")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void whenUsingEachDirRecurse_thenDirsAndSubDirsAreListed() {
|
||||
var files = []
|
||||
new File('src/main').eachDirRecurse { dir ->
|
||||
println "$dir.parent $dir.name"
|
||||
files.add("$dir.parent $dir.name")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void whenUsingTraverse_thenDirectoryIsTraversed() {
|
||||
var files = []
|
||||
new File('src/main').traverse { file ->
|
||||
if (file.directory && file.name == 'groovy') {
|
||||
FileVisitResult.SKIP_SUBTREE
|
||||
} else {
|
||||
println "$file.parent - $file.name"
|
||||
files.add("$file.parent - $file.name")
|
||||
}
|
||||
}
|
||||
assertTrue(files.size() > 1)
|
||||
}
|
||||
}
|
||||
|
@ -2,6 +2,8 @@ package groovy.com.baeldung.stringtypes
|
||||
|
||||
import org.junit.Test
|
||||
|
||||
import static org.junit.Assert.assertFalse
|
||||
|
||||
class DollarSlashyString {
|
||||
|
||||
@Test
|
||||
@ -19,6 +21,7 @@ class DollarSlashyString {
|
||||
- $/$$
|
||||
/$
|
||||
|
||||
print(dollarSlashy)
|
||||
//print(dollarSlashy)
|
||||
assertFalse(dollarSlashy.isEmpty())
|
||||
}
|
||||
}
|
||||
|
@ -45,8 +45,7 @@
|
||||
<properties>
|
||||
<maven.compiler.source.version>11</maven.compiler.source.version>
|
||||
<maven.compiler.target.version>11</maven.compiler.target.version>
|
||||
<jackson.version>2.16.0</jackson.version>
|
||||
<gson.version>2.10</gson.version>
|
||||
<gson.version>2.10.1</gson.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -0,0 +1,59 @@
|
||||
package com.baeldung.simplewebserver;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.file.Path;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
import com.sun.net.httpserver.Filter;
|
||||
import com.sun.net.httpserver.Headers;
|
||||
import com.sun.net.httpserver.HttpHandler;
|
||||
import com.sun.net.httpserver.HttpHandlers;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import com.sun.net.httpserver.Request;
|
||||
import com.sun.net.httpserver.SimpleFileServer;
|
||||
|
||||
public class WebServer {
|
||||
|
||||
private final InetSocketAddress address = new InetSocketAddress(8080);
|
||||
private final Path path = Path.of("/");
|
||||
|
||||
public static void main(String[] args) {
|
||||
WebServer webServer = new WebServer();
|
||||
HttpServer server = webServer.createWithHandler401Response();
|
||||
server.start();
|
||||
}
|
||||
|
||||
private HttpServer createBasic() {
|
||||
return SimpleFileServer.createFileServer(address, path, SimpleFileServer.OutputLevel.VERBOSE);
|
||||
}
|
||||
|
||||
private HttpServer createWithHandler() throws IOException {
|
||||
HttpServer server = SimpleFileServer.createFileServer(address, path, SimpleFileServer.OutputLevel.VERBOSE);
|
||||
HttpHandler handler = SimpleFileServer.createFileHandler(Path.of("/Users"));
|
||||
server.createContext("/test", handler);
|
||||
return server;
|
||||
}
|
||||
|
||||
private HttpServer createWithHandler401Response() {
|
||||
Predicate<Request> findAllowedPath = r -> r.getRequestURI()
|
||||
.getPath()
|
||||
.equals("/test/allowed");
|
||||
|
||||
HttpHandler allowedResponse = HttpHandlers.of(200, Headers.of("Allow", "GET"), "Welcome");
|
||||
HttpHandler deniedResponse = HttpHandlers.of(401, Headers.of("Deny", "GET"), "Denied");
|
||||
|
||||
HttpHandler handler = HttpHandlers.handleOrElse(findAllowedPath, allowedResponse, deniedResponse);
|
||||
|
||||
HttpServer server = SimpleFileServer.createFileServer(address, path, SimpleFileServer.OutputLevel.VERBOSE);
|
||||
server.createContext("/test", handler);
|
||||
return server;
|
||||
}
|
||||
|
||||
private HttpServer createWithFilter() throws IOException {
|
||||
Filter filter = SimpleFileServer.createOutputFilter(System.out, SimpleFileServer.OutputLevel.INFO);
|
||||
HttpHandler handler = SimpleFileServer.createFileHandler(Path.of("/Users"));
|
||||
return HttpServer.create(new InetSocketAddress(8080), 10, "/test", handler, filter);
|
||||
}
|
||||
|
||||
}
|
@ -63,7 +63,7 @@ public class VectorAPIExamples {
|
||||
public float[] scalarNormOfTwoArrays(float[] arr1, float[] arr2) {
|
||||
float[] finalResult = new float[arr1.length];
|
||||
for (int i = 0; i < arr1.length; i++) {
|
||||
finalResult[i] = (arr1[i] * arr1[i] + arr2[i] * arr2[i]) * -1.0f;
|
||||
finalResult[i] = (float) Math.sqrt(arr1[i] * arr1[i] + arr2[i] * arr2[i]);
|
||||
}
|
||||
return finalResult;
|
||||
}
|
||||
@ -77,13 +77,13 @@ public class VectorAPIExamples {
|
||||
var vb = FloatVector.fromArray(PREFERRED_SPECIES, arr2, i);
|
||||
var vc = va.mul(va)
|
||||
.add(vb.mul(vb))
|
||||
.neg();
|
||||
.sqrt();
|
||||
vc.intoArray(finalResult, i);
|
||||
}
|
||||
|
||||
// tail cleanup
|
||||
for (; i < arr1.length; i++) {
|
||||
finalResult[i] = (arr1[i] * arr1[i] + arr2[i] * arr2[i]) * -1.0f;
|
||||
finalResult[i] = (float) Math.sqrt(arr1[i] * arr1[i] + arr2[i] * arr2[i]);
|
||||
}
|
||||
return finalResult;
|
||||
}
|
||||
|
@ -28,7 +28,7 @@ public class VectorAPIUnitTest {
|
||||
public void whenTwoValuesProvided_thenComputeScalarNorm() {
|
||||
float[] arr1 = { 1, 2.3f };
|
||||
float[] arr2 = { 1.3f, 2.0f };
|
||||
float[] result = { -2.6899998f, -9.29f };
|
||||
float[] result = { 1.6401219f, 3.047950f };
|
||||
Assertions.assertArrayEquals(result, vector.scalarNormOfTwoArrays(arr1, arr2));
|
||||
}
|
||||
|
||||
@ -36,7 +36,7 @@ public class VectorAPIUnitTest {
|
||||
public void whenTwoValuesProvided_thenComputeVectorNorm() {
|
||||
float[] arr1 = { 1, 2.3f };
|
||||
float[] arr2 = { 1.3f, 2.0f };
|
||||
float[] result = { -2.6899998f, -9.29f };
|
||||
float[] result = { 1.6401219f, 3.047950f };
|
||||
Assertions.assertArrayEquals(result, vector.vectorNormalForm(arr1, arr2));
|
||||
}
|
||||
|
||||
|
@ -10,3 +10,4 @@ This module contains complete guides about arrays in Java
|
||||
- [Creating a Generic Array in Java](https://www.baeldung.com/java-generic-array)
|
||||
- [Maximum Size of Java Arrays](https://www.baeldung.com/java-arrays-max-size)
|
||||
- [Merge Two Arrays and Remove Duplicates in Java](https://www.baeldung.com/java-merge-two-arrays-delete-duplicates)
|
||||
- [Print a Java 2D Array](https://www.baeldung.com/java-2d-array-print)
|
||||
|
@ -7,10 +7,6 @@
|
||||
<name>core-java-arrays-guides</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<properties>
|
||||
<system-stubs.jupiter.version>2.1.5</system-stubs.jupiter.version>
|
||||
</properties>
|
||||
|
||||
<parent>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
@ -34,7 +30,10 @@
|
||||
<version>${system-stubs.jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<system-stubs.jupiter.version>2.1.5</system-stubs.jupiter.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
@ -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)
|
||||
|
@ -0,0 +1,24 @@
|
||||
package com.baeldung.equilibriumindex;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
class EquilibriumIndexFinder {
|
||||
|
||||
List<Integer> findEquilibriumIndexes(int[] array) {
|
||||
int[] partialSums = new int[array.length + 1];
|
||||
partialSums[0] = 0;
|
||||
for (int i = 0; i < array.length; i++) {
|
||||
partialSums[i+1] = partialSums[i] + array[i];
|
||||
}
|
||||
|
||||
List<Integer> equilibriumIndexes = new ArrayList<Integer>();
|
||||
for (int i = 0; i < array.length; i++) {
|
||||
if (partialSums[i] == (partialSums[array.length] - (partialSums[i+1]))) {
|
||||
equilibriumIndexes.add(i);
|
||||
}
|
||||
}
|
||||
return equilibriumIndexes;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,27 @@
|
||||
package com.baeldung.equilibriumindex;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class EquilibriumIndexFinderUnitTest {
|
||||
|
||||
@Test
|
||||
void givenArrayHasEquilibriumIndexes_whenFindEquilibriumIndexes_thenListAllEquilibriumIndexes() {
|
||||
int[] array = {1, -3, 0, 4, -5, 4, 0, 1, -2, -1};
|
||||
assertThat(new EquilibriumIndexFinder().findEquilibriumIndexes(array)).containsExactly(1, 4, 9);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenArrayWithoutEquilibriumIndexes_whenFindEquilibriumIndexes_thenEmptyList() {
|
||||
int[] array = {1, 2, 3};
|
||||
assertThat(new EquilibriumIndexFinder().findEquilibriumIndexes(array)).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenArrayWithOneElement_whenFindEquilibriumIndexes_thenListFirstIndex() {
|
||||
int[] array = {5};
|
||||
assertThat(new EquilibriumIndexFinder().findEquilibriumIndexes(array)).containsExactly(0);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,39 @@
|
||||
package com.baeldung.movezerototheend;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
|
||||
public class MoveZeroesToTheEndOfAnArrayUnitTest {
|
||||
private static final int[] EXPECTED = new int[] { 42, 2, 3, 4, 0, 0 };
|
||||
|
||||
@Test
|
||||
void whenCreatingANewArrayAndCopyingValues_thenGetTheExpectedResult() {
|
||||
int[] array = new int[] { 42, 2, 0, 3, 4, 0 };
|
||||
int[] result = new int[array.length];
|
||||
int idx = 0;
|
||||
for (int n : array) {
|
||||
if (n != 0) {
|
||||
result[idx++] = n;
|
||||
}
|
||||
}
|
||||
assertArrayEquals(EXPECTED, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenMovingZeroInTheOriginalArray_thenGetTheExpectedResult() {
|
||||
int[] array = new int[] { 42, 2, 0, 3, 4, 0 };
|
||||
int idx = 0;
|
||||
for (int n : array) {
|
||||
if (n != 0) {
|
||||
array[idx++] = n;
|
||||
}
|
||||
}
|
||||
while (idx < array.length) {
|
||||
array[idx++] = 0;
|
||||
}
|
||||
assertArrayEquals(EXPECTED, array);
|
||||
}
|
||||
}
|
@ -6,3 +6,4 @@ This module contains articles about Java Character Class
|
||||
- [Character#isAlphabetic vs. Character#isLetter](https://www.baeldung.com/java-character-isletter-isalphabetic)
|
||||
- [Difference Between Java’s “char” and “String”](https://www.baeldung.com/java-char-vs-string)
|
||||
- [Increment Character in Java](https://www.baeldung.com/java-char-sequence)
|
||||
- [Creating Unicode Character From Its Code Point Hex String](https://www.baeldung.com/java-unicode-character-from-code-point-hex-string)
|
||||
|
@ -5,18 +5,6 @@
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-collections-5</artifactId>
|
||||
<name>core-java-collections-5</name>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>9</source>
|
||||
<target>9</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
@ -61,6 +49,19 @@
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>9</source>
|
||||
<target>9</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<junit.version>5.9.2</junit.version>
|
||||
<roaringbitmap.version>0.9.38</roaringbitmap.version>
|
||||
|
@ -55,13 +55,11 @@
|
||||
<version>${org.json.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<jmh.version>1.21</jmh.version>
|
||||
<gson.version>2.10.1</gson.version>
|
||||
<jackson.version>2.16.0</jackson.version>
|
||||
<org.json.version>20230618</org.json.version>
|
||||
</properties>
|
||||
</project>
|
@ -27,7 +27,7 @@
|
||||
<dependency>
|
||||
<groupId>com.google.code.gson</groupId>
|
||||
<artifactId>gson</artifactId>
|
||||
<version>2.8.9</version>
|
||||
<version>2.10.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.json</groupId>
|
||||
|
@ -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)
|
||||
|
@ -32,17 +32,22 @@
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>32.1.2-jre</version>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>1.37</version>
|
||||
<version>${jmh.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>1.37</version>
|
||||
<version>${jmh.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>${commons-collections.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
@ -63,6 +68,9 @@
|
||||
<properties>
|
||||
<gson.version>2.10.1</gson.version>
|
||||
<csv.version>1.5</csv.version>
|
||||
<guava.version>32.1.2-jre</guava.version>
|
||||
<jmh.version>1.37</jmh.version>
|
||||
<commons-collections.version>4.4</commons-collections.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
@ -0,0 +1,111 @@
|
||||
package com.baeldung.map.entrysettolinkedhashmap;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.entry;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class EntrySetToLinkedHashMapUnitTest {
|
||||
|
||||
private Map<Integer, String> map;
|
||||
|
||||
@Test
|
||||
void givenMap_whenUsingCollectorsGroupingBy_thenCollectToLinkedHashMap() {
|
||||
Map<String, Set<String>> countryToCities = Map.of("Paris", "France", "Nice", "France", "Madrid", "Spain")
|
||||
.entrySet()
|
||||
.stream()
|
||||
.collect(Collectors.groupingBy(Map.Entry::getValue, LinkedHashMap::new, Collectors.mapping(Map.Entry::getKey, Collectors.toSet())));
|
||||
|
||||
assertThat(countryToCities).isExactlyInstanceOf(LinkedHashMap.class)
|
||||
.containsOnly(entry("France", Set.of("Paris", "Nice")), entry("Spain", Set.of("Madrid")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMap_whenUsingCollectorsToMap_thenCollectAndConvertToLinkedHashMap() {
|
||||
Map<Integer, String> result = new LinkedHashMap<>(map.entrySet()
|
||||
.stream()
|
||||
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
|
||||
|
||||
assertThat(result).isExactlyInstanceOf(LinkedHashMap.class)
|
||||
.containsOnly(entry(1, "value 1"), entry(2, "value 2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMap_whenUsingCollectorsToMap_thenCollectToLinkedHashMap() {
|
||||
Map<Integer, String> result = map.entrySet()
|
||||
.stream()
|
||||
.collect(Collectors.toMap(
|
||||
Map.Entry::getKey, Map.Entry::getValue,
|
||||
(e1, e2) -> {
|
||||
throw new RuntimeException();
|
||||
},
|
||||
LinkedHashMap::new));
|
||||
|
||||
assertThat(result).isExactlyInstanceOf(LinkedHashMap.class)
|
||||
.containsOnly(entry(1, "value 1"), entry(2, "value 2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMap_whenUsingLinkedHashMapConstructor_thenObtainLinkedHashMap() {
|
||||
Map<Integer, String> result = new LinkedHashMap<>(map);
|
||||
|
||||
assertThat(result).isExactlyInstanceOf(LinkedHashMap.class)
|
||||
.containsOnly(entry(1, "value 1"), entry(2, "value 2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMap_whenUsingPutWithForLoop_thenInsertIntoLinkedHashMap() {
|
||||
Map<Integer, String> result = new LinkedHashMap<>();
|
||||
|
||||
for (Map.Entry<Integer, String> entry : map.entrySet()) {
|
||||
result.put(entry.getKey(), entry.getValue());
|
||||
}
|
||||
|
||||
assertThat(result).isExactlyInstanceOf(LinkedHashMap.class)
|
||||
.containsOnly(entry(1, "value 1"), entry(2, "value 2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMap_whenUsingPutWithMapForEach_thenInsertIntoLinkedHashMap() {
|
||||
Map<Integer, String> result = new LinkedHashMap<>();
|
||||
|
||||
map.forEach((k, v) -> result.put(k, v));
|
||||
|
||||
assertThat(result).isExactlyInstanceOf(LinkedHashMap.class)
|
||||
.containsOnly(entry(1, "value 1"), entry(2, "value 2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMap_whenUsingPutWithSetForEach_thenInsertIntoLinkedHashMap() {
|
||||
Map<Integer, String> result = new LinkedHashMap<>();
|
||||
|
||||
map.entrySet()
|
||||
.forEach(entry -> result.put(entry.getKey(), entry.getValue()));
|
||||
|
||||
assertThat(result).isExactlyInstanceOf(LinkedHashMap.class)
|
||||
.containsOnly(entry(1, "value 1"), entry(2, "value 2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMap_whenUsingPutWithStreamForEach_thenInsertIntoLinkedHashMapp() {
|
||||
Map<Integer, String> result = new LinkedHashMap<>();
|
||||
|
||||
map.entrySet()
|
||||
.stream()
|
||||
.forEach(entry -> result.put(entry.getKey(), entry.getValue()));
|
||||
|
||||
assertThat(result).isExactlyInstanceOf(LinkedHashMap.class)
|
||||
.containsOnly(entry(1, "value 1"), entry(2, "value 2"));
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void init() {
|
||||
map = Map.of(1, "value 1", 2, "value 2");
|
||||
}
|
||||
}
|
@ -0,0 +1,202 @@
|
||||
package com.baeldung.map.prettyprintmap;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.google.common.base.Joiner;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import org.apache.commons.collections4.MapUtils;
|
||||
import org.assertj.core.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintStream;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
class PrettyPrintMapUnitTest {
|
||||
|
||||
private static final Map<String, Object> MAP;
|
||||
|
||||
static {
|
||||
// using LinkedHashMap to keep insertion order, helpful in assertions
|
||||
MAP = new LinkedHashMap<>();
|
||||
MAP.put("one", 1);
|
||||
MAP.put("two", 2);
|
||||
|
||||
Map<String, Integer> innerMap = new LinkedHashMap<>();
|
||||
innerMap.put("ten", 10);
|
||||
innerMap.put("eleven", 11);
|
||||
|
||||
MAP.put("inner", innerMap);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMap_whenToString_thenOneLine() {
|
||||
String result = MAP.toString();
|
||||
|
||||
String expected = "{one=1, two=2, inner={ten=10, eleven=11}}";
|
||||
Assertions.assertThat(result).isEqualTo(expected);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMap_whenSimpleForEachLoop_thenPrettyPrintWithoutNested() {
|
||||
StringBuilder result = new StringBuilder();
|
||||
|
||||
for (Map.Entry<?, ?> entry : MAP.entrySet()) {
|
||||
result.append(String.format("%-15s : %s%n", entry.getKey(), entry.getValue()));
|
||||
}
|
||||
|
||||
String expected =
|
||||
"one : 1\n" +
|
||||
"two : 2\n" +
|
||||
"inner : {ten=10, eleven=11}\n";
|
||||
Assertions.assertThat(result.toString()).isEqualToIgnoringNewLines(expected);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMap_whenRecursionForEachLoop_thenPrettyPrint() {
|
||||
String result = printMap(0, MAP);
|
||||
|
||||
String expected =
|
||||
"one : 1\n" +
|
||||
"two : 2\n" +
|
||||
"inner :\n" +
|
||||
" ten : 10\n" +
|
||||
" eleven : 11\n";
|
||||
Assertions.assertThat(result).isEqualToIgnoringNewLines(expected);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMap_whenStream_thenPrettyPrintWithoutNested() {
|
||||
StringBuilder result = new StringBuilder();
|
||||
|
||||
MAP.forEach((k, v) -> result.append(String.format("%-15s : %s%n", k, v)));
|
||||
|
||||
String expected =
|
||||
"one : 1\n" +
|
||||
"two : 2\n" +
|
||||
"inner : {ten=10, eleven=11}\n";
|
||||
Assertions.assertThat(result.toString()).isEqualToIgnoringNewLines(expected);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMap_whenExtendedStream_thenPrettyPrintWithoutNested() {
|
||||
String result = MAP.entrySet().stream()
|
||||
.map(entry -> String.format("%-15s : %s", entry.getKey(), entry.getValue()))
|
||||
.collect(Collectors.joining("\n"));
|
||||
|
||||
String expected =
|
||||
"one : 1\n" +
|
||||
"two : 2\n" +
|
||||
"inner : {ten=10, eleven=11}\n";
|
||||
Assertions.assertThat(result).isEqualToIgnoringNewLines(expected);
|
||||
}
|
||||
@Test
|
||||
void givenMap_whenJackson_thenPrettyPrint() throws JsonProcessingException {
|
||||
String result = new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(MAP);
|
||||
|
||||
String expected =
|
||||
"{\n" +
|
||||
" \"one\" : 1,\n" +
|
||||
" \"two\" : 2,\n" +
|
||||
" \"inner\" : {\n" +
|
||||
" \"ten\" : 10,\n" +
|
||||
" \"eleven\" : 11\n" +
|
||||
" }\n" +
|
||||
"}";
|
||||
Assertions.assertThat(result).isEqualToIgnoringNewLines(expected);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMap_whenGson_thenPrettyPrint() {
|
||||
String result = new GsonBuilder().setPrettyPrinting().create().toJson(MAP);
|
||||
|
||||
String expected =
|
||||
"{\n" +
|
||||
" \"one\": 1,\n" +
|
||||
" \"two\": 2,\n" +
|
||||
" \"inner\": {\n" +
|
||||
" \"ten\": 10,\n" +
|
||||
" \"eleven\": 11\n" +
|
||||
" }\n" +
|
||||
"}";
|
||||
Assertions.assertThat(result).isEqualToIgnoringNewLines(expected);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMap_whenApacheCommonsCollectionsDebugPrint_thenPrettyPrintWithClassNames() throws IOException {
|
||||
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
PrintStream ps = new PrintStream(baos)) {
|
||||
|
||||
MapUtils.debugPrint(ps, "map", MAP);
|
||||
String result = baos.toString();
|
||||
|
||||
String expected =
|
||||
"map = \n" +
|
||||
"{\n" +
|
||||
" one = 1 java.lang.Integer\n" +
|
||||
" two = 2 java.lang.Integer\n" +
|
||||
" inner = \n" +
|
||||
" {\n" +
|
||||
" ten = 10 java.lang.Integer\n" +
|
||||
" eleven = 11 java.lang.Integer\n" +
|
||||
" } java.util.LinkedHashMap\n" +
|
||||
"} java.util.LinkedHashMap\n";
|
||||
Assertions.assertThat(result).isEqualToIgnoringNewLines(expected);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMap_whenApacheCommonsCollectionsVerbosePrint_thenPrettyPrint() throws IOException {
|
||||
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
PrintStream ps = new PrintStream(baos)) {
|
||||
|
||||
MapUtils.verbosePrint(ps, "map", MAP);
|
||||
String result = baos.toString();
|
||||
|
||||
String expected =
|
||||
"map = \n" +
|
||||
"{\n" +
|
||||
" one = 1\n" +
|
||||
" two = 2\n" +
|
||||
" inner = \n" +
|
||||
" {\n" +
|
||||
" ten = 10\n" +
|
||||
" eleven = 11\n" +
|
||||
" }\n" +
|
||||
"}\n";
|
||||
Assertions.assertThat(result).isEqualToIgnoringNewLines(expected);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMap_whenGuavaJoiner_thenPrettyPrintWithoutNested() {
|
||||
String result = Joiner.on(",\n").withKeyValueSeparator("=").join(MAP);
|
||||
|
||||
String expected =
|
||||
"one=1,\n" +
|
||||
"two=2,\n" +
|
||||
"inner={ten=10, eleven=11}";
|
||||
Assertions.assertThat(result).isEqualToIgnoringNewLines(expected);
|
||||
}
|
||||
|
||||
private static String printMap(int leftPadding, Map<?, ?> map) {
|
||||
StringBuilder ret = new StringBuilder();
|
||||
|
||||
for (Map.Entry<?, ?> entry : map.entrySet()) {
|
||||
if (entry.getValue() instanceof Map) {
|
||||
ret.append(String.format("%-15s :%n", entry.getKey()));
|
||||
ret.append(printMap(leftPadding + 4, (Map<?, ?>) entry.getValue()));
|
||||
}
|
||||
else {
|
||||
ret.append(String.format("%" + (leftPadding > 0 ? leftPadding : "") + "s" // adding padding
|
||||
+ "%-15s : %s%n",
|
||||
"", entry.getKey(), entry.getValue()));
|
||||
}
|
||||
}
|
||||
return ret.toString();
|
||||
}
|
||||
|
||||
}
|
@ -41,7 +41,7 @@
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<gson.version>2.8.5</gson.version>
|
||||
<gson.version>2.10.1</gson.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -60,14 +60,15 @@ public class HashtableUnitTest {
|
||||
table.put(new Word("dog"), "another animal");
|
||||
|
||||
Iterator<Word> it = table.keySet().iterator();
|
||||
System.out.println("iterator created");
|
||||
// System.out.println("iterator created");
|
||||
|
||||
table.remove(new Word("dog"));
|
||||
System.out.println("element removed");
|
||||
// System.out.println("element removed");
|
||||
|
||||
while (it.hasNext()) {
|
||||
Word key = it.next();
|
||||
System.out.println(table.get(key));
|
||||
// System.out.println(table.get(key));
|
||||
assertNotNull(table.get(key));
|
||||
}
|
||||
}
|
||||
|
||||
@ -85,12 +86,13 @@ public class HashtableUnitTest {
|
||||
table.put(new Word("8"), "eight");
|
||||
|
||||
Enumeration<Word> enumKey = table.keys();
|
||||
System.out.println("Enumeration created");
|
||||
// System.out.println("Enumeration created");
|
||||
table.remove(new Word("1"));
|
||||
System.out.println("element removed");
|
||||
// System.out.println("element removed");
|
||||
while (enumKey.hasMoreElements()) {
|
||||
Word key = enumKey.nextElement();
|
||||
System.out.println(table.get(key));
|
||||
// System.out.println(table.get(key));
|
||||
assertNotNull(table.get(key));
|
||||
}
|
||||
}
|
||||
|
||||
@ -110,7 +112,8 @@ public class HashtableUnitTest {
|
||||
Iterator<Map.Entry<Word, String>> it = table.entrySet().iterator();
|
||||
while (it.hasNext()) {
|
||||
Map.Entry<Word, String> entry = it.next();
|
||||
System.out.println(entry.getValue());
|
||||
// System.out.println(entry.getValue());
|
||||
assertNotNull(entry.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -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)
|
||||
|
@ -0,0 +1,79 @@
|
||||
package com.baeldung.runvssupply;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
|
||||
public class RunAndSupplyCompare {
|
||||
|
||||
public static void main(String args[]) throws ExecutionException, InterruptedException {
|
||||
chainingOperationCompare();
|
||||
}
|
||||
|
||||
public static void inputAndReturnCompare() throws ExecutionException, InterruptedException {
|
||||
CompletableFuture<Void> runAsyncFuture = CompletableFuture.runAsync(() -> {
|
||||
// Perform non-result producing task
|
||||
System.out.println("Task executed asynchronously");
|
||||
});
|
||||
|
||||
CompletableFuture<String> supplyAsyncFuture = CompletableFuture.supplyAsync(() -> {
|
||||
// Perform result-producing task
|
||||
return "Result of the asynchronous computation";
|
||||
});
|
||||
// Get the result later
|
||||
String result = supplyAsyncFuture.get();
|
||||
System.out.println("Result: " + result);
|
||||
}
|
||||
|
||||
public static void exceptionHandlingCompare() {
|
||||
CompletableFuture<Void> runAsyncFuture = CompletableFuture.runAsync(() -> {
|
||||
// Task that may throw an exception
|
||||
throw new RuntimeException("Exception occurred in asynchronous task");
|
||||
});
|
||||
try {
|
||||
runAsyncFuture.get();
|
||||
// Exception will be thrown here
|
||||
} catch (ExecutionException ex) {
|
||||
Throwable cause = ex.getCause();
|
||||
System.out.println("Exception caught: " + cause.getMessage());
|
||||
} catch (InterruptedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
CompletableFuture<Object> supplyAsyncFuture = CompletableFuture.supplyAsync(() -> {
|
||||
// Task that may throw an exception
|
||||
throw new RuntimeException("Exception occurred in asynchronous task");
|
||||
})
|
||||
.exceptionally(ex -> {
|
||||
// Exception handling logic
|
||||
return "Default value";
|
||||
});
|
||||
|
||||
Object result = supplyAsyncFuture.join();
|
||||
// Get the result or default value
|
||||
System.out.println("Result: " + result);
|
||||
}
|
||||
|
||||
public static void chainingOperationCompare() {
|
||||
CompletableFuture<Void> runAsyncFuture = CompletableFuture.runAsync(() -> {
|
||||
// Perform non-result producing task
|
||||
System.out.println("Task executed asynchronously");
|
||||
});
|
||||
runAsyncFuture.thenRun(() -> {
|
||||
// Execute another task after the completion of runAsync()
|
||||
System.out.println("Another task executed after runAsync() completes");
|
||||
});
|
||||
|
||||
CompletableFuture<String> supplyAsyncFuture = CompletableFuture.supplyAsync(() -> {
|
||||
// Perform result-producing task
|
||||
return "Result of the asynchronous computation";
|
||||
});
|
||||
supplyAsyncFuture.thenApply(result -> {
|
||||
// Transform the result
|
||||
return result.toUpperCase();
|
||||
})
|
||||
.thenAccept(transformedResult -> {
|
||||
// Consume the transformed result
|
||||
System.out.println("Transformed Result: " + transformedResult);
|
||||
});
|
||||
}
|
||||
}
|
@ -0,0 +1,91 @@
|
||||
package com.baeldung.concurrent.applyvsapplyasync;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
public class ThenApplyAndThenApplyAsyncUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenCompletableFuture_whenUsingThenApply_thenResultIsAsExpected() {
|
||||
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 5);
|
||||
CompletableFuture<String> thenApplyResultFuture = future.thenApply(num -> "Result: " + num);
|
||||
|
||||
String thenApplyResult = thenApplyResultFuture.join();
|
||||
assertEquals("Result: 5", thenApplyResult);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCompletableFuture_whenUsingThenApplyAsync_thenResultIsAsExpected() {
|
||||
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 5);
|
||||
CompletableFuture<String> thenApplyAsyncResultFuture = future.thenApplyAsync(num -> "Result: " + num);
|
||||
|
||||
String thenApplyAsyncResult = thenApplyAsyncResultFuture.join();
|
||||
assertEquals("Result: 5", thenApplyAsyncResult);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCompletableFuture_whenUsingThenApply_thenExceptionIsPropagated() {
|
||||
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 5);
|
||||
CompletableFuture<String> resultFuture = future.thenApply(num -> "Result: " + num / 0);
|
||||
assertThrows(CompletionException.class, () -> resultFuture.join());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCompletableFuture_whenUsingThenApply_thenExceptionIsHandledAsExpected() {
|
||||
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 5);
|
||||
CompletableFuture<String> resultFuture = future.thenApply(num -> "Result: " + num / 0);
|
||||
try {
|
||||
// Accessing the result
|
||||
String result = resultFuture.join();
|
||||
assertEquals("Result: 5", result);
|
||||
} catch (CompletionException e) {
|
||||
assertEquals("java.lang.ArithmeticException: / by zero", e.getMessage());
|
||||
System.err.println("Exception caught: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCompletableFuture_whenUsingThenApplyAsync_thenExceptionIsHandledAsExpected() {
|
||||
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 5);
|
||||
CompletableFuture<String> thenApplyAsyncResultFuture = future.thenApplyAsync(num -> "Result: " + num / 0);
|
||||
|
||||
String result = thenApplyAsyncResultFuture.handle((res, error) -> {
|
||||
if (error != null) {
|
||||
// Handle the error appropriately, e.g., return a default value
|
||||
return "Error occurred";
|
||||
} else {
|
||||
return res;
|
||||
}
|
||||
})
|
||||
.join(); // Now join() won't throw the exception
|
||||
assertEquals("Error occurred", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCompletableFutureWithExecutor_whenUsingThenApplyAsync_thenThreadExecutesAsExpected() {
|
||||
ExecutorService customExecutor = Executors.newFixedThreadPool(4);
|
||||
|
||||
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
|
||||
try {
|
||||
Thread.sleep(2000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return 5;
|
||||
}, customExecutor);
|
||||
|
||||
CompletableFuture<String> resultFuture = future.thenApplyAsync(num -> "Result: " + num, customExecutor);
|
||||
|
||||
String result = resultFuture.join();
|
||||
assertEquals("Result: 5", result);
|
||||
|
||||
customExecutor.shutdown();
|
||||
}
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
@ -2,3 +2,4 @@
|
||||
### Relevant Articles:
|
||||
- [Why wait() Requires Synchronization?](https://www.baeldung.com/java-wait-necessary-synchronization)
|
||||
- [Working with Exceptions in Java CompletableFuture](https://www.baeldung.com/java-exceptions-completablefuture)
|
||||
- [CountDownLatch vs. Semaphore](https://www.baeldung.com/java-countdownlatch-vs-semaphore)
|
||||
|
@ -0,0 +1,33 @@
|
||||
package com.baeldung.countdownlatchvssemaphore;
|
||||
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
|
||||
public class CountDownLatchDemo {
|
||||
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
// Create a CountDownLatch with an initial count equal to the number of tasks to be completed
|
||||
int numberOfTasks = 3;
|
||||
CountDownLatch latch = new CountDownLatch(numberOfTasks);
|
||||
|
||||
// Simulate completion of tasks by worker threads
|
||||
for (int i = 1; i <= numberOfTasks; i++) {
|
||||
new Thread(() -> {
|
||||
System.out.println("Task completed by Thread " + Thread.currentThread()
|
||||
.getId());
|
||||
|
||||
// Decrement the latch count to signal completion of a task
|
||||
latch.countDown();
|
||||
}).start();
|
||||
}
|
||||
|
||||
// Main thread waits until all tasks are completed
|
||||
latch.await();
|
||||
System.out.println("All tasks completed. Main thread proceeds.");
|
||||
|
||||
// Attempting to reset will have no effect
|
||||
latch.countDown();
|
||||
// Latch is already at zero, await() returns immediately
|
||||
latch.await(); // This line won't block
|
||||
System.out.println("Latch is already at zero and cannot be reset.");
|
||||
}
|
||||
}
|
@ -0,0 +1,42 @@
|
||||
package com.baeldung.countdownlatchvssemaphore;
|
||||
|
||||
import java.util.concurrent.Semaphore;
|
||||
|
||||
public class SemaphoreDemo {
|
||||
|
||||
public static void main(String[] args) {
|
||||
// Create a Semaphore with a fixed number of permits
|
||||
int NUM_PERMITS = 3;
|
||||
Semaphore semaphore = new Semaphore(NUM_PERMITS);
|
||||
|
||||
// Simulate resource access by worker threads
|
||||
for (int i = 1; i <= 5; i++) {
|
||||
new Thread(() -> {
|
||||
try {
|
||||
// Acquire a permit to access the resource
|
||||
semaphore.acquire();
|
||||
System.out.println("Thread " + Thread.currentThread().getId() + " accessing resource.");
|
||||
|
||||
// Simulate resource usage
|
||||
Thread.sleep(2000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
// Release the permit after resource access is complete
|
||||
semaphore.release();
|
||||
}
|
||||
}).start();
|
||||
}
|
||||
|
||||
// Simulate resetting the Semaphore by releasing additional permits after a delay
|
||||
try {
|
||||
Thread.sleep(5000);
|
||||
|
||||
// Resetting the semaphore permits to the initial count
|
||||
semaphore.release(NUM_PERMITS);
|
||||
System.out.println("Semaphore permits reset to initial count.");
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
@ -9,3 +9,4 @@
|
||||
- [How to Log to the Console in Color](https://www.baeldung.com/java-log-console-in-color)
|
||||
- [Create Table Using ASCII in a Console in Java](https://www.baeldung.com/java-console-ascii-make-table)
|
||||
- [Printing Message on Console without Using main() Method in Java](https://www.baeldung.com/java-no-main-print-message-console)
|
||||
- [Guide to System.in.read()](https://www.baeldung.com/java-system-in-read)
|
||||
|
@ -0,0 +1,45 @@
|
||||
package com.baeldung.systemin;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
class SystemInRead {
|
||||
static void readSingleCharacter() {
|
||||
System.out.println("Enter a character:");
|
||||
try {
|
||||
int input = System.in.read();
|
||||
System.out.println((char) input);
|
||||
}
|
||||
catch (IOException e) {
|
||||
System.err.println("Error reading input: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
static void readMultipleCharacters() {
|
||||
System.out.println("Enter characters (Press 'Enter' to quit):");
|
||||
try {
|
||||
int input;
|
||||
while ((input = System.in.read()) != '\n') {
|
||||
System.out.print((char) input);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
System.err.println("Error reading input: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
static void readWithParameters() {
|
||||
try {
|
||||
byte[] byteArray = new byte[5];
|
||||
int bytesRead;
|
||||
int totalBytesRead = 0;
|
||||
|
||||
while ((bytesRead = System.in.read(byteArray, 0, byteArray.length)) != -1) {
|
||||
System.out.print("Data read: " + new String(byteArray, 0, bytesRead));
|
||||
totalBytesRead += bytesRead;
|
||||
}
|
||||
|
||||
System.out.println("\nBytes Read: " + totalBytesRead);
|
||||
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,41 @@
|
||||
package com.baeldung.systemin;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.PrintStream;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class SystemInReadUnitTest {
|
||||
@Test
|
||||
void givenUserInput_whenUsingReadMultipleCharacters_thenRead() {
|
||||
System.setIn(new ByteArrayInputStream("Hello\n".getBytes()));
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
System.setOut(new PrintStream(outputStream));
|
||||
SystemInRead.readMultipleCharacters();
|
||||
|
||||
assertEquals("Enter characters (Press 'Enter' to quit):\n" + "Hello", outputStream.toString().trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenUserInput_whenUsingReadSingleCharacter_thenRead() {
|
||||
System.setIn(new ByteArrayInputStream("A".getBytes()));
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
System.setOut(new PrintStream(outputStream));
|
||||
SystemInRead.readSingleCharacter();
|
||||
|
||||
assertEquals("Enter a character:\nA", outputStream.toString().trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenUserInput_whenUsingReadWithParameters_thenRead() {
|
||||
System.setIn(new ByteArrayInputStream("ABC".getBytes()));
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
System.setOut(new PrintStream(outputStream));
|
||||
SystemInRead.readWithParameters();
|
||||
|
||||
assertEquals("Data read: ABC\n" + "Bytes Read: 3", outputStream.toString().trim());
|
||||
}
|
||||
}
|
@ -3,4 +3,5 @@ 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)
|
||||
|
@ -0,0 +1,65 @@
|
||||
package com.baeldung.datetounixtimestamp;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.GregorianCalendar;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import org.joda.time.DateTime;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class DateToUnixTimeStampUnitTest {
|
||||
|
||||
@Test
|
||||
void givenDate_whenUsingInstantClass_thenConvertToUnixTimeStamp() {
|
||||
Instant givenDate = Instant.parse("2020-09-08T12:16:40Z");
|
||||
|
||||
assertEquals(1599567400L, givenDate.getEpochSecond());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenDate_whenUsingLocalDateTimeClass_thenConvertToUnixTimeStamp() {
|
||||
LocalDateTime givenDate = LocalDateTime.of(2023, 10, 19, 22, 45);
|
||||
|
||||
assertEquals(1697755500L, givenDate.toEpochSecond(ZoneOffset.UTC));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenDate_whenUsingDateClass_thenConvertToUnixTimeStamp() throws ParseException {
|
||||
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
|
||||
Date givenDate = dateFormat.parse("2023-10-15 22:00:00");
|
||||
|
||||
assertEquals(1697407200L, givenDate.getTime() / 1000);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenDate_whenUsingCalendarClass_thenConvertToUnixTimeStamp() {
|
||||
Calendar calendar = new GregorianCalendar(2023, Calendar.OCTOBER, 17);
|
||||
calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
|
||||
|
||||
assertEquals(1697500800L, calendar.getTimeInMillis() / 1000);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenDate_whenUsingJodaTimeInstantClass_thenConvertToUnixTimeStamp() {
|
||||
org.joda.time.Instant givenDate = org.joda.time.Instant.parse("2020-09-08T12:16:40Z");
|
||||
|
||||
assertEquals(1599567400L, givenDate.getMillis() / 1000);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenDate_whenUsingJodaTimeDateTimeClass_thenConvertToUnixTimeStamp() {
|
||||
DateTime givenDate = new DateTime("2020-09-09T12:16:40Z");
|
||||
|
||||
assertEquals(1599653800L, givenDate.getMillis() / 1000);
|
||||
}
|
||||
|
||||
}
|
@ -3,4 +3,5 @@
|
||||
This module contains articles about converting between Java date and time objects.
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- [Convert Gregorian to Hijri Date in Java](https://www.baeldung.com/java-date-gregorian-hijri-conversion)
|
||||
- [Convert String Date to XMLGregorianCalendar in Java](https://www.baeldung.com/java-string-date-xmlgregoriancalendar-conversion)
|
||||
|
@ -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>
|
||||
|
||||
|
@ -4,7 +4,7 @@ import java.util.function.Function;
|
||||
|
||||
public class Currying {
|
||||
|
||||
private static Function<Double, Function<Double, Double>> weight = mass -> gravity -> mass * gravity;
|
||||
private static Function<Double, Function<Double, Double>> weight = gravity -> mass -> mass * gravity;
|
||||
|
||||
private static Function<Double, Double> weightOnEarth = weight.apply(9.81);
|
||||
|
||||
|
@ -0,0 +1,16 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
|
||||
<logger name="org.eclipse.jetty.server.handler" level="WARN"/>
|
||||
<logger name="org.mockserver.log" level="WARN"/>
|
||||
</configuration>
|
@ -8,5 +8,6 @@ This module contains articles about core Java input and output (IO)
|
||||
- [Difference Between ZipFile and ZipInputStream in Java](https://www.baeldung.com/java-zipfile-vs-zipinputstream)
|
||||
- [How to Write Strings to OutputStream in Java](https://www.baeldung.com/java-write-string-outputstream)
|
||||
- [Read a File and Split It Into Multiple Files in Java](https://www.baeldung.com/java-read-file-split-into-several)
|
||||
- [Read and Write Files in Java Using Separate Threads](https://www.baeldung.com/java-read-write-files-different-threads)
|
||||
- [[<-- Prev]](/core-java-modules/core-java-io-4)
|
||||
|
||||
|
1
core-java-modules/core-java-io-5/file.txt
Normal file
1
core-java-modules/core-java-io-5/file.txt
Normal file
@ -0,0 +1 @@
|
||||
Hello, world!
|
@ -0,0 +1,85 @@
|
||||
package com.baeldung.readwritethread;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.FileReader;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
|
||||
public class ReadWriteBlockingQueue {
|
||||
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
|
||||
BlockingQueue<String> queue = new LinkedBlockingQueue<>();
|
||||
String readFileName = "src/main/resources/read_file.txt";
|
||||
String writeFileName = "src/main/resources/write_file.txt";
|
||||
|
||||
Thread producerThread = new Thread(new FileProducer(queue, readFileName));
|
||||
Thread consumerThread1 = new Thread(new FileConsumer(queue, writeFileName));
|
||||
|
||||
producerThread.start();
|
||||
Thread.sleep(100); // Give producer a head start
|
||||
consumerThread1.start();
|
||||
try {
|
||||
producerThread.join();
|
||||
consumerThread1.join();
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
class FileProducer implements Runnable {
|
||||
|
||||
private final BlockingQueue<String> queue;
|
||||
private final String inputFileName;
|
||||
|
||||
public FileProducer(BlockingQueue<String> queue, String inputFileName) {
|
||||
this.queue = queue;
|
||||
this.inputFileName = inputFileName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try (BufferedReader reader = new BufferedReader(new FileReader(inputFileName))) {
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
queue.offer(line);
|
||||
System.out.println("Producer added line: " + line);
|
||||
System.out.println("Queue size: " + queue.size());
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class FileConsumer implements Runnable {
|
||||
|
||||
private final BlockingQueue<String> queue;
|
||||
private final String outputFileName;
|
||||
|
||||
public FileConsumer(BlockingQueue queue, String outputFileName) {
|
||||
this.queue = queue;
|
||||
this.outputFileName = outputFileName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFileName))) {
|
||||
String line;
|
||||
while ((line = queue.poll()) != null) {
|
||||
writer.write(line);
|
||||
writer.newLine();
|
||||
System.out.println(Thread.currentThread()
|
||||
.getId() + " - Consumer processed line: " + line);
|
||||
System.out.println("Queue size: " + queue.size());
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,55 @@
|
||||
package com.baeldung.readwritethread;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.FileReader;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
|
||||
public class ReadWriteThread {
|
||||
|
||||
public static void readFile(String filePath) {
|
||||
Thread thread = new Thread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath))) {
|
||||
String line;
|
||||
while ((line = bufferedReader.readLine()) != null) {
|
||||
System.out.println(line);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
});
|
||||
thread.start();
|
||||
}
|
||||
|
||||
public static void writeFile(String filePath, String content) {
|
||||
Thread thread = new Thread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try (FileWriter fileWriter = new FileWriter(filePath)) {
|
||||
fileWriter.write("Hello, world!");
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
});
|
||||
thread.start();
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
String file = "src/main/resources/text.txt";
|
||||
|
||||
writeFile(file, "Hello, world!");
|
||||
|
||||
readFile(file);
|
||||
|
||||
// Sleep for a while to allow the threads to complete
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,5 @@
|
||||
Hello,
|
||||
Baeldung!
|
||||
Nice to meet you!
|
||||
My name is
|
||||
Wynn.
|
@ -0,0 +1 @@
|
||||
Hello, world!
|
@ -0,0 +1,5 @@
|
||||
Hello,
|
||||
Baeldung!
|
||||
Nice to meet you!
|
||||
My name is
|
||||
Wynn.
|
@ -82,6 +82,7 @@
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-io-apis-2</finalName>
|
||||
<resources>
|
||||
@ -91,6 +92,7 @@
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<junit-jupiter-version>5.9.3</junit-jupiter-version>
|
||||
</properties>
|
||||
|
@ -51,9 +51,10 @@ public class ReadInputCharByCharUnitTest {
|
||||
System.setIn(inputStream);
|
||||
|
||||
try (Scanner scanner = new Scanner(System.in)) {
|
||||
char[] result = scanner.next().toCharArray();
|
||||
|
||||
assertArrayEquals("TestInput".toCharArray(), result);
|
||||
if (scanner.hasNext()) {
|
||||
char[] result = scanner.next().toCharArray();
|
||||
assertArrayEquals("TestInput".toCharArray(), result);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -37,7 +37,7 @@
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<compiler.plugin.version>3.8.0</compiler.plugin.version>
|
||||
<compiler.plugin.version>3.12.1</compiler.plugin.version>
|
||||
<source.version>11</source.version>
|
||||
<target.version>11</target.version>
|
||||
</properties>
|
||||
|
@ -37,7 +37,7 @@
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<compiler.plugin.version>3.8.0</compiler.plugin.version>
|
||||
<compiler.plugin.version>3.12.1</compiler.plugin.version>
|
||||
<source.version>11</source.version>
|
||||
<target.version>11</target.version>
|
||||
</properties>
|
||||
|
@ -14,3 +14,4 @@ This module contains articles about core features in the Java language
|
||||
- [Static Final Variables in Java](https://www.baeldung.com/java-static-final-variables)
|
||||
- [What Is the Error: “Non-static method cannot be referenced from a static context”?](https://www.baeldung.com/java-non-static-method-cannot-be-referenced-from-a-static-context)
|
||||
- [Recursively Sum the Integers in an Array](https://www.baeldung.com/java-recursive-sum-integer-array)
|
||||
- [Set an Environment Variable at Runtime in Java](https://www.baeldung.com/java-set-environment-variable-runtime)
|
||||
|
@ -3,14 +3,14 @@
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
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-lang-6</artifactId>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>core-java-lang-6</artifactId>
|
||||
|
||||
<dependencies>
|
||||
<!-- https://mvnrepository.com/artifact/org.mapstruct/mapstruct -->
|
||||
<dependency>
|
||||
|
@ -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];
|
||||
}
|
||||
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
@ -5,6 +5,14 @@
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-lang-math</artifactId>
|
||||
<name>core-java-lang-math</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.projectlombok</groupId>
|
||||
@ -13,13 +21,6 @@
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-lang-math</finalName>
|
||||
|
@ -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)
|
||||
|
@ -32,7 +32,7 @@
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<gson.version>2.8.2</gson.version>
|
||||
<gson.version>2.10.1</gson.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -0,0 +1,21 @@
|
||||
package com.baeldung.objectmutability;
|
||||
|
||||
public final class ImmutablePerson {
|
||||
|
||||
private final String name;
|
||||
private final int age;
|
||||
|
||||
public ImmutablePerson(String name, int age) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,33 @@
|
||||
package com.baeldung.objectmutability;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotSame;
|
||||
|
||||
public class ImmutableObjectExamplesUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenImmutableString_whenConcatString_thenNotSameAndCorrectValues() {
|
||||
String originalString = "Hello";
|
||||
String modifiedString = originalString.concat(" World");
|
||||
|
||||
assertNotSame(originalString, modifiedString);
|
||||
|
||||
assertEquals("Hello", originalString);
|
||||
assertEquals("Hello World", modifiedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenImmutableInteger_whenAddInteger_thenNotSameAndCorrectValue() {
|
||||
Integer immutableInt = 42;
|
||||
Integer modifiedInt = immutableInt + 8;
|
||||
|
||||
assertNotSame(immutableInt, modifiedInt);
|
||||
|
||||
assertEquals(42, (int) immutableInt);
|
||||
assertEquals(50, (int) modifiedInt);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -0,0 +1,17 @@
|
||||
package com.baeldung.objectmutability;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class ImmutablePersonUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenImmutablePerson_whenAccessFields_thenCorrectValues() {
|
||||
ImmutablePerson person = new ImmutablePerson("John", 30);
|
||||
|
||||
assertEquals("John", person.getName());
|
||||
assertEquals(30, person.getAge());
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,28 @@
|
||||
package com.baeldung.objectmutability;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class MutableObjectExamplesUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenMutableString_whenAppendElement_thenCorrectValue() {
|
||||
StringBuilder mutableString = new StringBuilder("Hello");
|
||||
mutableString.append(" World");
|
||||
|
||||
assertEquals("Hello World", mutableString.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMutableList_whenAddElement_thenCorrectSize() {
|
||||
List<String> mutableList = new ArrayList<>();
|
||||
mutableList.add("Java");
|
||||
|
||||
assertEquals(1, mutableList.size());
|
||||
}
|
||||
}
|
||||
|
@ -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)
|
||||
|
@ -0,0 +1,67 @@
|
||||
package com.baeldung.infixpostfix;
|
||||
|
||||
import java.util.Stack;
|
||||
|
||||
public class InfixToPostFixExpressionConversion {
|
||||
|
||||
private int getPrecedenceScore(char ch) {
|
||||
switch (ch) {
|
||||
case '^':
|
||||
return 3;
|
||||
|
||||
case '*':
|
||||
case '/':
|
||||
return 2;
|
||||
|
||||
case '+':
|
||||
case '-':
|
||||
return 1;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
private boolean isOperand(char ch) {
|
||||
return (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9');
|
||||
}
|
||||
|
||||
private char associativity(char ch) {
|
||||
if (ch == '^')
|
||||
return 'R';
|
||||
return 'L';
|
||||
}
|
||||
|
||||
public String infixToPostfix(String infix) {
|
||||
StringBuilder result = new StringBuilder();
|
||||
Stack<Character> stack = new Stack<>();
|
||||
|
||||
for (int i = 0; i < infix.length(); i++) {
|
||||
char ch = infix.charAt(i);
|
||||
|
||||
if (isOperand(ch)) {
|
||||
result.append(ch);
|
||||
} else if (ch == '(') {
|
||||
stack.push(ch);
|
||||
} else if (ch == ')') {
|
||||
while (!stack.isEmpty() && stack.peek() != '(') {
|
||||
result.append(stack.pop());
|
||||
}
|
||||
stack.pop();
|
||||
} else {
|
||||
while (!stack.isEmpty() && (operatorPrecedenceCondition(infix, i, stack))) {
|
||||
result.append(stack.pop());
|
||||
}
|
||||
stack.push(ch);
|
||||
}
|
||||
}
|
||||
|
||||
while (!stack.isEmpty()) {
|
||||
result.append(stack.pop());
|
||||
}
|
||||
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
private boolean operatorPrecedenceCondition(String infix, int i, Stack<Character> stack) {
|
||||
return getPrecedenceScore(infix.charAt(i)) < getPrecedenceScore(stack.peek()) || getPrecedenceScore(infix.charAt(i)) == getPrecedenceScore(stack.peek()) && associativity(infix.charAt(i)) == 'L';
|
||||
}
|
||||
}
|
@ -0,0 +1,37 @@
|
||||
package com.baeldung.infixpostfix;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
|
||||
public class InfixToPostfixExpressionUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenSimpleOp_whenNoParenthesis_thenProduceValidPostfix() {
|
||||
String infix = "a+b*c-d";
|
||||
String postfix = "abc*+d-";
|
||||
|
||||
InfixToPostFixExpressionConversion obj = new InfixToPostFixExpressionConversion();
|
||||
|
||||
Assertions.assertEquals(postfix, obj.infixToPostfix(infix));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSimpleOp_whenWithParenthesis_thenProduceValidPostfix() {
|
||||
String infix = "(a+b)*(c-d)";
|
||||
String postfix = "ab+cd-*";
|
||||
|
||||
InfixToPostFixExpressionConversion obj = new InfixToPostFixExpressionConversion();
|
||||
|
||||
Assertions.assertEquals(postfix, obj.infixToPostfix(infix));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenComplexOp_whenInputIsInfix_thenProduceValidPostfix() {
|
||||
String infix = "a^b*(c^d-e)^(f+g*h)-i";
|
||||
String postfix = "ab^cd^e-fgh*+^*i-";
|
||||
|
||||
InfixToPostFixExpressionConversion obj = new InfixToPostFixExpressionConversion();
|
||||
|
||||
Assertions.assertEquals(postfix, obj.infixToPostfix(infix));
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user