Merge branch 'eugenp:master' into master
This commit is contained in:
commit
9c2c32a279
|
@ -0,0 +1,7 @@
|
||||||
|
## Akka HTTP
|
||||||
|
|
||||||
|
This module contains articles about Akka actors.
|
||||||
|
|
||||||
|
### Relevant articles:
|
||||||
|
|
||||||
|
- [Introduction to Akka Actors in Java](https://www.baeldung.com/akka-actors-java)
|
|
@ -0,0 +1,33 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<artifactId>akka-actors</artifactId>
|
||||||
|
<name>akka-actors</name>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>akka-modules</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.typesafe.akka</groupId>
|
||||||
|
<artifactId>akka-actor_${scala.version}</artifactId>
|
||||||
|
<version>${typesafe-akka.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.typesafe.akka</groupId>
|
||||||
|
<artifactId>akka-testkit_${scala.version}</artifactId>
|
||||||
|
<version>${typesafe-akka.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<typesafe-akka.version>2.5.11</typesafe-akka.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
</project>
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.akka;
|
package com.baeldung.akkaactors;
|
||||||
|
|
||||||
import akka.actor.AbstractActor;
|
import akka.actor.AbstractActor;
|
||||||
import akka.actor.Props;
|
import akka.actor.Props;
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.akka;
|
package com.baeldung.akkaactors;
|
||||||
|
|
||||||
import akka.actor.AbstractActor;
|
import akka.actor.AbstractActor;
|
||||||
import akka.event.Logging;
|
import akka.event.Logging;
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.akka;
|
package com.baeldung.akkaactors;
|
||||||
|
|
||||||
import akka.actor.AbstractActor;
|
import akka.actor.AbstractActor;
|
||||||
import akka.actor.Props;
|
import akka.actor.Props;
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.akka;
|
package com.baeldung.akkaactors;
|
||||||
|
|
||||||
import akka.actor.AbstractActor;
|
import akka.actor.AbstractActor;
|
||||||
import akka.actor.ActorRef;
|
import akka.actor.ActorRef;
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.akka;
|
package com.baeldung.akkaactors;
|
||||||
|
|
||||||
import akka.actor.AbstractActor;
|
import akka.actor.AbstractActor;
|
||||||
import akka.event.Logging;
|
import akka.event.Logging;
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.akka;
|
package com.baeldung.akkaactors;
|
||||||
|
|
||||||
import akka.actor.ActorRef;
|
import akka.actor.ActorRef;
|
||||||
import akka.actor.ActorSystem;
|
import akka.actor.ActorSystem;
|
|
@ -14,6 +14,7 @@
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<modules>
|
<modules>
|
||||||
|
<module>akka-actors</module>
|
||||||
<module>akka-http</module>
|
<module>akka-http</module>
|
||||||
<module>akka-streams</module>
|
<module>akka-streams</module>
|
||||||
<module>spring-akka</module>
|
<module>spring-akka</module>
|
||||||
|
|
|
@ -63,11 +63,6 @@
|
||||||
<version>${wiremock.version}</version>
|
<version>${wiremock.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
|
||||||
<groupId>org.apache.httpcomponents</groupId>
|
|
||||||
<artifactId>httpclient</artifactId>
|
|
||||||
<version>${httpclient.version}</version>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
|
@ -84,10 +79,9 @@
|
||||||
<mockserver.version>5.6.1</mockserver.version>
|
<mockserver.version>5.6.1</mockserver.version>
|
||||||
<wiremock.version>3.3.1</wiremock.version>
|
<wiremock.version>3.3.1</wiremock.version>
|
||||||
<!-- http client & core 5 -->
|
<!-- http client & core 5 -->
|
||||||
<httpcore5.version>5.2</httpcore5.version>
|
<httpcore5.version>5.2.2</httpcore5.version>
|
||||||
<httpclient5.version>5.2</httpclient5.version>
|
<httpclient5.version>5.2.2</httpclient5.version>
|
||||||
<httpclient5-fluent.version>5.2</httpclient5-fluent.version>
|
<httpclient5-fluent.version>5.2.2</httpclient5-fluent.version>
|
||||||
<httpclient.version>4.5.14</httpclient.version>
|
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
|
|
@ -25,6 +25,7 @@ import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBu
|
||||||
import org.apache.hc.client5.http.impl.routing.DefaultProxyRoutePlanner;
|
import org.apache.hc.client5.http.impl.routing.DefaultProxyRoutePlanner;
|
||||||
import org.apache.hc.client5.http.protocol.HttpClientContext;
|
import org.apache.hc.client5.http.protocol.HttpClientContext;
|
||||||
import org.apache.hc.client5.http.ssl.ClientTlsStrategyBuilder;
|
import org.apache.hc.client5.http.ssl.ClientTlsStrategyBuilder;
|
||||||
|
import org.apache.hc.client5.http.ssl.NoopHostnameVerifier;
|
||||||
import org.apache.hc.core5.http.HttpHost;
|
import org.apache.hc.core5.http.HttpHost;
|
||||||
import org.apache.hc.core5.http.HttpResponse;
|
import org.apache.hc.core5.http.HttpResponse;
|
||||||
import org.apache.hc.core5.http.nio.ssl.TlsStrategy;
|
import org.apache.hc.core5.http.nio.ssl.TlsStrategy;
|
||||||
|
@ -33,7 +34,6 @@ import org.apache.hc.core5.http.protocol.HttpContext;
|
||||||
import org.apache.hc.core5.reactor.IOReactorConfig;
|
import org.apache.hc.core5.reactor.IOReactorConfig;
|
||||||
import org.apache.hc.core5.ssl.SSLContexts;
|
import org.apache.hc.core5.ssl.SSLContexts;
|
||||||
import org.apache.hc.core5.ssl.TrustStrategy;
|
import org.apache.hc.core5.ssl.TrustStrategy;
|
||||||
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
|
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
|
||||||
|
@ -120,7 +120,7 @@ class HttpAsyncClientLiveTest extends GetRequestMockServer {
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
final TlsStrategy tlsStrategy = ClientTlsStrategyBuilder.create()
|
final TlsStrategy tlsStrategy = ClientTlsStrategyBuilder.create()
|
||||||
.setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
|
.setHostnameVerifier(NoopHostnameVerifier.INSTANCE)
|
||||||
.setSslContext(sslContext)
|
.setSslContext(sslContext)
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
|
|
|
@ -55,15 +55,15 @@
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.fasterxml.jackson.core</groupId>
|
<groupId>com.fasterxml.jackson.core</groupId>
|
||||||
<artifactId>jackson-databind</artifactId>
|
<artifactId>jackson-databind</artifactId>
|
||||||
<version>${jackson.databind.version} </version>
|
<version>${jackson.databind.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<jna.version>5.7.0</jna.version>
|
<jna.version>5.7.0</jna.version>
|
||||||
<kafka.version>2.8.0</kafka.version>
|
<kafka.version>3.6.1</kafka.version>
|
||||||
<testcontainers-kafka.version>1.15.3</testcontainers-kafka.version>
|
<testcontainers-kafka.version>1.19.3</testcontainers-kafka.version>
|
||||||
<testcontainers-jupiter.version>1.15.3</testcontainers-jupiter.version>
|
<testcontainers-jupiter.version>1.19.3</testcontainers-jupiter.version>
|
||||||
<jackson.databind.version>2.15.2</jackson.databind.version>
|
<jackson.databind.version>2.15.2</jackson.databind.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,56 @@
|
||||||
|
package com.baeldung.kafka.consumer;
|
||||||
|
|
||||||
|
import java.io.Closeable;
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Properties;
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
|
import org.apache.kafka.clients.consumer.ConsumerConfig;
|
||||||
|
import org.apache.kafka.clients.consumer.KafkaConsumer;
|
||||||
|
import org.apache.kafka.common.serialization.StringDeserializer;
|
||||||
|
|
||||||
|
public class CustomKafkaListener implements Runnable {
|
||||||
|
private static final Logger log = Logger.getLogger(CustomKafkaListener.class.getName());
|
||||||
|
private final String topic;
|
||||||
|
private final KafkaConsumer<String, String> consumer;
|
||||||
|
private Consumer<String> recordConsumer;
|
||||||
|
|
||||||
|
|
||||||
|
public CustomKafkaListener(String topic, KafkaConsumer<String, String> consumer) {
|
||||||
|
this.topic = topic;
|
||||||
|
this.consumer = consumer;
|
||||||
|
this.recordConsumer = record -> log.info("received: " + record);
|
||||||
|
}
|
||||||
|
|
||||||
|
public CustomKafkaListener(String topic, String bootstrapServers) {
|
||||||
|
this(topic, defaultKafkaConsumer(bootstrapServers));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static KafkaConsumer<String, String> defaultKafkaConsumer(String boostrapServers) {
|
||||||
|
Properties props = new Properties();
|
||||||
|
props.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, boostrapServers);
|
||||||
|
props.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "test_group_id");
|
||||||
|
props.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
|
||||||
|
props.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
|
||||||
|
props.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
|
||||||
|
return new KafkaConsumer<>(props);
|
||||||
|
}
|
||||||
|
|
||||||
|
public CustomKafkaListener onEach(Consumer<String> newConsumer) {
|
||||||
|
recordConsumer = recordConsumer.andThen(newConsumer);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
consumer.subscribe(Arrays.asList(topic));
|
||||||
|
while (true) {
|
||||||
|
consumer.poll(Duration.ofMillis(100))
|
||||||
|
.forEach(record -> recordConsumer.accept(record.value()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,82 @@
|
||||||
|
package com.baeldung.kafka.consumer;
|
||||||
|
|
||||||
|
import static java.time.Duration.ofMillis;
|
||||||
|
import static java.time.Duration.ofSeconds;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.testcontainers.shaded.org.awaitility.Awaitility.await;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Properties;
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
|
||||||
|
import org.apache.kafka.clients.producer.KafkaProducer;
|
||||||
|
import org.apache.kafka.clients.producer.ProducerConfig;
|
||||||
|
import org.apache.kafka.clients.producer.ProducerRecord;
|
||||||
|
import org.apache.kafka.common.serialization.StringSerializer;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.testcontainers.containers.KafkaContainer;
|
||||||
|
import org.testcontainers.junit.jupiter.Container;
|
||||||
|
import org.testcontainers.junit.jupiter.Testcontainers;
|
||||||
|
import org.testcontainers.shaded.org.awaitility.Awaitility;
|
||||||
|
import org.testcontainers.utility.DockerImageName;
|
||||||
|
|
||||||
|
@Testcontainers
|
||||||
|
class CustomKafkaListenerLiveTest {
|
||||||
|
|
||||||
|
@Container
|
||||||
|
private static final KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:latest"));
|
||||||
|
|
||||||
|
static {
|
||||||
|
Awaitility.setDefaultTimeout(ofSeconds(5L));
|
||||||
|
Awaitility.setDefaultPollInterval(ofMillis(50L));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenANewCustomKafkaListener_thenConsumesAllMessages() {
|
||||||
|
// given
|
||||||
|
String topic = "baeldung.articles.published";
|
||||||
|
String bootstrapServers = KAFKA_CONTAINER.getBootstrapServers();
|
||||||
|
List<String> consumedMessages = new ArrayList<>();
|
||||||
|
|
||||||
|
// when
|
||||||
|
CustomKafkaListener listener = new CustomKafkaListener(topic, bootstrapServers).onEach(consumedMessages::add);
|
||||||
|
CompletableFuture.runAsync(listener);
|
||||||
|
|
||||||
|
// and
|
||||||
|
publishArticles(topic,
|
||||||
|
"Introduction to Kafka",
|
||||||
|
"Kotlin for Java Developers",
|
||||||
|
"Reactive Spring Boot",
|
||||||
|
"Deploying Spring Boot Applications",
|
||||||
|
"Spring Security"
|
||||||
|
);
|
||||||
|
|
||||||
|
// then
|
||||||
|
await().untilAsserted(() ->
|
||||||
|
assertThat(consumedMessages).containsExactlyInAnyOrder(
|
||||||
|
"Introduction to Kafka",
|
||||||
|
"Kotlin for Java Developers",
|
||||||
|
"Reactive Spring Boot",
|
||||||
|
"Deploying Spring Boot Applications",
|
||||||
|
"Spring Security"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void publishArticles(String topic, String... articles) {
|
||||||
|
try (KafkaProducer<String, String> producer = testKafkaProducer()) {
|
||||||
|
Arrays.stream(articles)
|
||||||
|
.map(article -> new ProducerRecord<>(topic, "key-1", article))
|
||||||
|
.forEach(producer::send);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static KafkaProducer<String, String> testKafkaProducer() {
|
||||||
|
Properties props = new Properties();
|
||||||
|
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers());
|
||||||
|
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
|
||||||
|
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
|
||||||
|
return new KafkaProducer<>(props);
|
||||||
|
}
|
||||||
|
}
|
|
@ -181,8 +181,9 @@
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
|
<jackson.version>2.13.4</jackson.version>
|
||||||
<kafka.version>3.4.0</kafka.version>
|
<kafka.version>3.4.0</kafka.version>
|
||||||
<testcontainers-kafka.version>1.15.3</testcontainers-kafka.version>
|
<testcontainers-kafka.version>1.19.3</testcontainers-kafka.version>
|
||||||
<testcontainers-jupiter.version>1.15.3</testcontainers-jupiter.version>
|
<testcontainers-jupiter.version>1.15.3</testcontainers-jupiter.version>
|
||||||
<flink.version>1.16.1</flink.version>
|
<flink.version>1.16.1</flink.version>
|
||||||
<awaitility.version>3.0.0</awaitility.version>
|
<awaitility.version>3.0.0</awaitility.version>
|
||||||
|
|
|
@ -29,7 +29,7 @@ import java.util.List;
|
||||||
import static org.junit.Assert.assertArrayEquals;
|
import static org.junit.Assert.assertArrayEquals;
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
public class BackupCreatorIntegrationTest {
|
public class BackupCreatorUnitTest {
|
||||||
public static ObjectMapper mapper;
|
public static ObjectMapper mapper;
|
||||||
|
|
||||||
@Before
|
@Before
|
|
@ -10,7 +10,7 @@ import java.util.Arrays;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
public class WordCapitalizerIntegrationTest {
|
public class WordCapitalizerUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenDataSet_whenExecuteWordCapitalizer_thenReturnCapitalizedWords() throws Exception {
|
public void givenDataSet_whenExecuteWordCapitalizer_thenReturnCapitalizedWords() throws Exception {
|
|
@ -21,8 +21,7 @@ import org.junit.Ignore;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class KafkaStreamsLiveTest {
|
public class KafkaStreamsLiveTest {
|
||||||
private String bootstrapServers = "localhost:9092";
|
private final String bootstrapServers = "localhost:9092";
|
||||||
private Path stateDirectory;
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@Ignore("it needs to have kafka broker running on local")
|
@Ignore("it needs to have kafka broker running on local")
|
||||||
|
@ -44,8 +43,8 @@ public class KafkaStreamsLiveTest {
|
||||||
|
|
||||||
// Use a temporary directory for storing state, which will be automatically removed after the test.
|
// Use a temporary directory for storing state, which will be automatically removed after the test.
|
||||||
try {
|
try {
|
||||||
this.stateDirectory = Files.createTempDirectory("kafka-streams");
|
Path stateDirectory = Files.createTempDirectory("kafka-streams");
|
||||||
streamsConfiguration.put(StreamsConfig.STATE_DIR_CONFIG, this.stateDirectory.toAbsolutePath()
|
streamsConfiguration.put(StreamsConfig.STATE_DIR_CONFIG, stateDirectory.toAbsolutePath()
|
||||||
.toString());
|
.toString());
|
||||||
} catch (final IOException e) {
|
} catch (final IOException e) {
|
||||||
throw new UncheckedIOException("Cannot create temporary directory", e);
|
throw new UncheckedIOException("Cannot create temporary directory", e);
|
||||||
|
|
|
@ -1,7 +0,0 @@
|
||||||
## ASM
|
|
||||||
|
|
||||||
This module contains articles about ASM
|
|
||||||
|
|
||||||
### Relevant Articles:
|
|
||||||
|
|
||||||
- [A Guide to Java Bytecode Manipulation with ASM](https://www.baeldung.com/java-asm)
|
|
54
asm/pom.xml
54
asm/pom.xml
|
@ -1,54 +0,0 @@
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
|
||||||
<modelVersion>4.0.0</modelVersion>
|
|
||||||
<groupId>com.baeldung.examples</groupId>
|
|
||||||
<artifactId>asm</artifactId>
|
|
||||||
<version>1.0</version>
|
|
||||||
<name>asm</name>
|
|
||||||
<packaging>jar</packaging>
|
|
||||||
|
|
||||||
<parent>
|
|
||||||
<groupId>com.baeldung</groupId>
|
|
||||||
<artifactId>parent-modules</artifactId>
|
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
|
||||||
</parent>
|
|
||||||
|
|
||||||
<dependencies>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.ow2.asm</groupId>
|
|
||||||
<artifactId>asm</artifactId>
|
|
||||||
<version>${asm.version}</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.ow2.asm</groupId>
|
|
||||||
<artifactId>asm-util</artifactId>
|
|
||||||
<version>${asm.version}</version>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
|
||||||
|
|
||||||
<build>
|
|
||||||
<plugins>
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-jar-plugin</artifactId>
|
|
||||||
<version>${maven-jar-plugin.version}</version>
|
|
||||||
<configuration>
|
|
||||||
<archive>
|
|
||||||
<manifestEntries>
|
|
||||||
<Premain-Class>
|
|
||||||
com.baeldung.examples.asm.instrumentation.Premain
|
|
||||||
</Premain-Class>
|
|
||||||
</manifestEntries>
|
|
||||||
</archive>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
</plugins>
|
|
||||||
</build>
|
|
||||||
|
|
||||||
<properties>
|
|
||||||
<asm.version>5.2</asm.version>
|
|
||||||
</properties>
|
|
||||||
|
|
||||||
</project>
|
|
|
@ -1,7 +1,7 @@
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
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>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<artifactId>aws-dynamodb</artifactId>
|
<artifactId>aws-dynamodb</artifactId>
|
||||||
<version>0.1.0-SNAPSHOT</version>
|
<version>0.1.0-SNAPSHOT</version>
|
||||||
|
@ -40,22 +40,6 @@
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
<plugins>
|
<plugins>
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-shade-plugin</artifactId>
|
|
||||||
<version>${maven-shade-plugin.version}</version>
|
|
||||||
<configuration>
|
|
||||||
<createDependencyReducedPom>false</createDependencyReducedPom>
|
|
||||||
</configuration>
|
|
||||||
<executions>
|
|
||||||
<execution>
|
|
||||||
<phase>package</phase>
|
|
||||||
<goals>
|
|
||||||
<goal>shade</goal>
|
|
||||||
</goals>
|
|
||||||
</execution>
|
|
||||||
</executions>
|
|
||||||
</plugin>
|
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-dependency-plugin</artifactId>
|
<artifactId>maven-dependency-plugin</artifactId>
|
||||||
|
|
|
@ -34,22 +34,6 @@
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
<plugins>
|
<plugins>
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-shade-plugin</artifactId>
|
|
||||||
<version>${maven-shade-plugin.version}</version>
|
|
||||||
<configuration>
|
|
||||||
<createDependencyReducedPom>false</createDependencyReducedPom>
|
|
||||||
</configuration>
|
|
||||||
<executions>
|
|
||||||
<execution>
|
|
||||||
<phase>package</phase>
|
|
||||||
<goals>
|
|
||||||
<goal>shade</goal>
|
|
||||||
</goals>
|
|
||||||
</execution>
|
|
||||||
</executions>
|
|
||||||
</plugin>
|
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-dependency-plugin</artifactId>
|
<artifactId>maven-dependency-plugin</artifactId>
|
||||||
|
|
|
@ -63,6 +63,7 @@
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>io.projectreactor</groupId>
|
<groupId>io.projectreactor</groupId>
|
||||||
<artifactId>reactor-test</artifactId>
|
<artifactId>reactor-test</artifactId>
|
||||||
|
<version>${reactor.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
|
@ -93,7 +94,7 @@
|
||||||
<properties>
|
<properties>
|
||||||
<spring.version>2.2.1.RELEASE</spring.version>
|
<spring.version>2.2.1.RELEASE</spring.version>
|
||||||
<awssdk.version>2.17.283</awssdk.version>
|
<awssdk.version>2.17.283</awssdk.version>
|
||||||
<lombok.version>1.18.20</lombok.version>
|
<reactor.version>3.6.0</reactor.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
|
@ -39,27 +39,6 @@
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
|
||||||
<plugins>
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-shade-plugin</artifactId>
|
|
||||||
<version>${maven-shade-plugin.version}</version>
|
|
||||||
<configuration>
|
|
||||||
<createDependencyReducedPom>false</createDependencyReducedPom>
|
|
||||||
</configuration>
|
|
||||||
<executions>
|
|
||||||
<execution>
|
|
||||||
<phase>package</phase>
|
|
||||||
<goals>
|
|
||||||
<goal>shade</goal>
|
|
||||||
</goals>
|
|
||||||
</execution>
|
|
||||||
</executions>
|
|
||||||
</plugin>
|
|
||||||
</plugins>
|
|
||||||
</build>
|
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<aws.java.sdk.version>2.20.52</aws.java.sdk.version>
|
<aws.java.sdk.version>2.20.52</aws.java.sdk.version>
|
||||||
<commons-codec-version>1.10.L001</commons-codec-version>
|
<commons-codec-version>1.10.L001</commons-codec-version>
|
||||||
|
|
|
@ -5,6 +5,13 @@
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<artifactId>aws-modules</artifactId>
|
<artifactId>aws-modules</artifactId>
|
||||||
<name>aws-modules</name>
|
<name>aws-modules</name>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>parent-modules</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.amazonaws</groupId>
|
<groupId>com.amazonaws</groupId>
|
||||||
|
@ -15,12 +22,6 @@
|
||||||
</dependencies>
|
</dependencies>
|
||||||
<packaging>pom</packaging>
|
<packaging>pom</packaging>
|
||||||
|
|
||||||
<parent>
|
|
||||||
<groupId>com.baeldung</groupId>
|
|
||||||
<artifactId>parent-modules</artifactId>
|
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
|
||||||
</parent>
|
|
||||||
|
|
||||||
<modules>
|
<modules>
|
||||||
<module>aws-app-sync</module>
|
<module>aws-app-sync</module>
|
||||||
<module>aws-dynamodb</module>
|
<module>aws-dynamodb</module>
|
||||||
|
|
|
@ -167,7 +167,6 @@
|
||||||
<properties>
|
<properties>
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
<commons-lang3.version>3.9</commons-lang3.version>
|
<commons-lang3.version>3.9</commons-lang3.version>
|
||||||
<java.version>1.8</java.version>
|
|
||||||
<logback.version>1.2.3</logback.version>
|
<logback.version>1.2.3</logback.version>
|
||||||
</properties>
|
</properties>
|
||||||
</project>
|
</project>
|
||||||
|
|
|
@ -13,6 +13,13 @@
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
|
<pluginRepositories>
|
||||||
|
<pluginRepository>
|
||||||
|
<id>groovy-plugins-release</id>
|
||||||
|
<url>https://groovy.jfrog.io/artifactory/plugins-release-local</url>
|
||||||
|
</pluginRepository>
|
||||||
|
</pluginRepositories>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.commons</groupId>
|
<groupId>org.apache.commons</groupId>
|
||||||
|
@ -156,8 +163,8 @@
|
||||||
<groovy-wslite.version>1.1.3</groovy-wslite.version>
|
<groovy-wslite.version>1.1.3</groovy-wslite.version>
|
||||||
<assembly.plugin.version>3.4.2</assembly.plugin.version>
|
<assembly.plugin.version>3.4.2</assembly.plugin.version>
|
||||||
<compiler.plugin.version>3.8.1</compiler.plugin.version>
|
<compiler.plugin.version>3.8.1</compiler.plugin.version>
|
||||||
<groovy.compiler.version>3.7.0</groovy.compiler.version>
|
<groovy.compiler.version>3.9.0</groovy.compiler.version>
|
||||||
<groovy-eclipse-batch.version>3.0.8-01</groovy-eclipse-batch.version>
|
<groovy-eclipse-batch.version>3.0.9-03</groovy-eclipse-batch.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
|
|
@ -45,7 +45,7 @@
|
||||||
<properties>
|
<properties>
|
||||||
<maven.compiler.source.version>11</maven.compiler.source.version>
|
<maven.compiler.source.version>11</maven.compiler.source.version>
|
||||||
<maven.compiler.target.version>11</maven.compiler.target.version>
|
<maven.compiler.target.version>11</maven.compiler.target.version>
|
||||||
<jackson.version>2.14.1</jackson.version>
|
<jackson.version>2.16.0</jackson.version>
|
||||||
<gson.version>2.10</gson.version>
|
<gson.version>2.10</gson.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
|
|
|
@ -21,8 +21,4 @@
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<properties>
|
|
||||||
<java.version>17</java.version>
|
|
||||||
</properties>
|
|
||||||
|
|
||||||
</project>
|
</project>
|
|
@ -13,8 +13,4 @@
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<properties>
|
|
||||||
<java.version>17</java.version>
|
|
||||||
</properties>
|
|
||||||
|
|
||||||
</project>
|
</project>
|
|
@ -26,8 +26,4 @@
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<properties>
|
|
||||||
<java.version>17</java.version>
|
|
||||||
</properties>
|
|
||||||
|
|
||||||
</project>
|
</project>
|
|
@ -1,3 +1,4 @@
|
||||||
## Relevant Articles
|
## Relevant Articles
|
||||||
- [Scoped Values in Java 20](https://www.baeldung.com/java-20-scoped-values)
|
- [Scoped Values in Java 20](https://www.baeldung.com/java-20-scoped-values)
|
||||||
- [How to Read Zip Files Entries With Java](https://www.baeldung.com/java-read-zip-files)
|
- [How to Read Zip Files Entries With Java](https://www.baeldung.com/java-read-zip-files)
|
||||||
|
- [Deserializing JSON to Java Record using Gson](https://www.baeldung.com/java-json-deserialize-record-gson)
|
||||||
|
|
|
@ -3,19 +3,34 @@
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
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>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<artifactId>core-java-20</artifactId>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung.core-java-modules</groupId>
|
<groupId>com.baeldung.core-java-modules</groupId>
|
||||||
<artifactId>core-java-modules</artifactId>
|
<artifactId>core-java-modules</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<artifactId>core-java-20</artifactId>
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
<properties>
|
<groupId>jakarta.servlet</groupId>
|
||||||
<maven.compiler.source>20</maven.compiler.source>
|
<artifactId>jakarta.servlet-api</artifactId>
|
||||||
<maven.compiler.target>20</maven.compiler.target>
|
<version>6.0.0</version>
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
<scope>provided</scope>
|
||||||
</properties>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.assertj</groupId>
|
||||||
|
<artifactId>assertj-core</artifactId>
|
||||||
|
<version>3.24.2</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.mockito</groupId>
|
||||||
|
<artifactId>mockito-junit-jupiter</artifactId>
|
||||||
|
<version>5.2.0</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
<plugins>
|
<plugins>
|
||||||
|
@ -41,25 +56,10 @@
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
<dependencies>
|
<properties>
|
||||||
<dependency>
|
<maven.compiler.source>20</maven.compiler.source>
|
||||||
<groupId>jakarta.servlet</groupId>
|
<maven.compiler.target>20</maven.compiler.target>
|
||||||
<artifactId>jakarta.servlet-api</artifactId>
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
<version>6.0.0</version>
|
</properties>
|
||||||
<scope>provided</scope>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.assertj</groupId>
|
|
||||||
<artifactId>assertj-core</artifactId>
|
|
||||||
<version>3.24.2</version>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.mockito</groupId>
|
|
||||||
<artifactId>mockito-junit-jupiter</artifactId>
|
|
||||||
<version>5.2.0</version>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
|
||||||
|
|
||||||
</project>
|
</project>
|
|
@ -0,0 +1,5 @@
|
||||||
|
package com.baeldung.deserialization;
|
||||||
|
|
||||||
|
public record Contact(String email, String phone) {
|
||||||
|
// Constructor, getters, and other methods are automatically generated
|
||||||
|
}
|
|
@ -0,0 +1,5 @@
|
||||||
|
package com.baeldung.deserialization;
|
||||||
|
|
||||||
|
public record Person(String name, int age, String address, Contact contact) {
|
||||||
|
// Constructor, getters, and other methods are automatically generated
|
||||||
|
}
|
|
@ -0,0 +1,39 @@
|
||||||
|
package com.baeldung.deserialization;
|
||||||
|
|
||||||
|
import com.google.gson.Gson;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertNotNull;
|
||||||
|
|
||||||
|
public class DeserializationUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenJsonString_whenDeserialized_thenPersonRecordCreated() {
|
||||||
|
String json = "{\"name\":\"John Doe\",\"age\":30,\"address\":\"123 Main St\"}";
|
||||||
|
|
||||||
|
Person person = new Gson().fromJson(json, Person.class);
|
||||||
|
|
||||||
|
assertEquals("John Doe", person.name());
|
||||||
|
assertEquals(30, person.age());
|
||||||
|
assertEquals("123 Main St", person.address());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenNestedJsonString_whenDeserialized_thenPersonRecordCreated() {
|
||||||
|
String json = "{\"name\":\"John Doe\",\"age\":30,\"address\":\"123 Main St\",\"contact\":{\"email\":\"john.doe@example.com\",\"phone\":\"555-1234\"}}";
|
||||||
|
|
||||||
|
Person person = new Gson().fromJson(json, Person.class);
|
||||||
|
|
||||||
|
assertNotNull(person);
|
||||||
|
assertEquals("John Doe", person.name());
|
||||||
|
assertEquals(30, person.age());
|
||||||
|
assertEquals("123 Main St", person.address());
|
||||||
|
|
||||||
|
Contact contact = person.contact();
|
||||||
|
|
||||||
|
assertNotNull(contact);
|
||||||
|
assertEquals("john.doe@example.com", contact.email());
|
||||||
|
assertEquals("555-1234", contact.phone());
|
||||||
|
}
|
||||||
|
}
|
|
@ -8,4 +8,5 @@
|
||||||
- [Add Minutes to a Time String in Java](https://www.baeldung.com/java-string-time-add-mins)
|
- [Add Minutes to a Time String in Java](https://www.baeldung.com/java-string-time-add-mins)
|
||||||
- [Round the Date in Java](https://www.baeldung.com/java-round-the-date)
|
- [Round the Date in Java](https://www.baeldung.com/java-round-the-date)
|
||||||
- [Representing Furthest Possible Date in Java](https://www.baeldung.com/java-date-represent-max)
|
- [Representing Furthest Possible Date in Java](https://www.baeldung.com/java-date-represent-max)
|
||||||
|
- [Retrieving Unix Time in Java](https://www.baeldung.com/java-retrieve-unix-time)
|
||||||
- [[<-- Prev]](/core-java-modules/core-java-datetime-java8-1)
|
- [[<-- Prev]](/core-java-modules/core-java-datetime-java8-1)
|
||||||
|
|
|
@ -0,0 +1,44 @@
|
||||||
|
package com.baeldung.localdatetoiso;
|
||||||
|
|
||||||
|
import java.text.DateFormat;
|
||||||
|
import java.text.SimpleDateFormat;
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.ZoneOffset;
|
||||||
|
import java.time.format.DateTimeFormatter;
|
||||||
|
import java.util.Date;
|
||||||
|
|
||||||
|
import org.apache.commons.lang3.time.DateFormatUtils;
|
||||||
|
|
||||||
|
import org.joda.time.DateTime;
|
||||||
|
import org.joda.time.DateTimeZone;
|
||||||
|
import org.joda.time.format.DateTimeFormat;
|
||||||
|
import org.joda.time.format.ISODateTimeFormat;
|
||||||
|
|
||||||
|
import org.apache.commons.lang3.time.FastDateFormat;
|
||||||
|
|
||||||
|
public class LocalDateToISO {
|
||||||
|
public String formatUsingDateTimeFormatter(LocalDate localDate) {
|
||||||
|
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX");
|
||||||
|
String formattedDate = localDate.atStartOfDay().atOffset(ZoneOffset.UTC).format(formatter);
|
||||||
|
return formattedDate;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String formatUsingSimpleDateFormat(LocalDate date) {
|
||||||
|
Date utilDate = Date.from(date.atStartOfDay(ZoneOffset.UTC).toInstant());
|
||||||
|
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
|
||||||
|
String formattedDate = dateFormat.format(utilDate);
|
||||||
|
return formattedDate;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String formatUsingJodaTime(org.joda.time.LocalDate localDate) {
|
||||||
|
org.joda.time.format.DateTimeFormatter formatter = ISODateTimeFormat.dateTime();
|
||||||
|
return formatter.print(localDate.toDateTimeAtStartOfDay(DateTimeZone.UTC));
|
||||||
|
}
|
||||||
|
|
||||||
|
public String formatUsingApacheCommonsLang(LocalDate localDate) {
|
||||||
|
Date date = Date.from(localDate.atStartOfDay().toInstant(ZoneOffset.UTC));
|
||||||
|
String formattedDate = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss.sss'Z'", TimeZone.getTimeZone("UTC"))
|
||||||
|
.format(date);
|
||||||
|
return formattedDate;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,44 @@
|
||||||
|
package com.baeldung.monthintervalbetweentwodates;
|
||||||
|
|
||||||
|
import java.util.Calendar;
|
||||||
|
import java.util.Date;
|
||||||
|
|
||||||
|
public class MonthInterval {
|
||||||
|
|
||||||
|
public int monthsBetween(Date startDate, Date endDate) {
|
||||||
|
if (startDate == null || endDate == null) {
|
||||||
|
throw new IllegalArgumentException("Both startDate and endDate must be provided");
|
||||||
|
}
|
||||||
|
|
||||||
|
Calendar startCalendar = Calendar.getInstance();
|
||||||
|
startCalendar.setTime(startDate);
|
||||||
|
int startDateTotalMonths = 12 * startCalendar.get(Calendar.YEAR) + startCalendar.get(Calendar.MONTH);
|
||||||
|
|
||||||
|
Calendar endCalendar = Calendar.getInstance();
|
||||||
|
endCalendar.setTime(endDate);
|
||||||
|
int endDateTotalMonths = 12 * endCalendar.get(Calendar.YEAR) + endCalendar.get(Calendar.MONTH);
|
||||||
|
|
||||||
|
return endDateTotalMonths - startDateTotalMonths;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int monthsBetweenWithDayValue(Date startDate, Date endDate) {
|
||||||
|
if (startDate == null || endDate == null) {
|
||||||
|
throw new IllegalArgumentException("Both startDate and endDate must be provided");
|
||||||
|
}
|
||||||
|
|
||||||
|
Calendar startCalendar = Calendar.getInstance();
|
||||||
|
startCalendar.setTime(startDate);
|
||||||
|
|
||||||
|
int startDateDayOfMonth = startCalendar.get(Calendar.DAY_OF_MONTH);
|
||||||
|
int startDateTotalMonths = 12 * startCalendar.get(Calendar.YEAR) + startCalendar.get(Calendar.MONTH);
|
||||||
|
|
||||||
|
Calendar endCalendar = Calendar.getInstance();
|
||||||
|
endCalendar.setTime(endDate);
|
||||||
|
|
||||||
|
int endDateDayOfMonth = endCalendar.get(Calendar.DAY_OF_MONTH);
|
||||||
|
int endDateTotalMonths = 12 * endCalendar.get(Calendar.YEAR) + endCalendar.get(Calendar.MONTH);
|
||||||
|
|
||||||
|
return (startDateDayOfMonth > endDateDayOfMonth) ? (endDateTotalMonths - startDateTotalMonths) - 1 : (endDateTotalMonths - startDateTotalMonths);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,48 @@
|
||||||
|
package com.baeldung.localdatetoiso;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
import java.time.LocalDate;
|
||||||
|
|
||||||
|
public class LocalDateToISOUnitTest {
|
||||||
|
@Test
|
||||||
|
void givenLocalDate_whenUsingDateTimeFormatter_thenISOFormat(){
|
||||||
|
LocalDateToISO localDateToISO = new LocalDateToISO();
|
||||||
|
LocalDate localDate = LocalDate.of(2023, 11, 6);
|
||||||
|
|
||||||
|
String expected = "2023-11-06T00:00:00.000Z";
|
||||||
|
String actual = localDateToISO.formatUsingDateTimeFormatter(localDate);
|
||||||
|
assertEquals(expected, actual);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenLocalDate_whenUsingSimpleDateFormat_thenISOFormat(){
|
||||||
|
LocalDateToISO localDateToISO = new LocalDateToISO();
|
||||||
|
LocalDate localDate = LocalDate.of(2023, 11, 6);
|
||||||
|
|
||||||
|
String expected = "2023-11-06T00:00:00.000Z";
|
||||||
|
String actual = localDateToISO.formatUsingSimpleDateFormat(localDate);
|
||||||
|
assertEquals(expected, actual);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenLocalDate_whenUsingJodaTime_thenISOFormat() {
|
||||||
|
LocalDateToISO localDateToISO = new LocalDateToISO();
|
||||||
|
org.joda.time.LocalDate localDate = new org.joda.time.LocalDate(2023, 11, 6);
|
||||||
|
|
||||||
|
String expected = "2023-11-06T00:00:00.000Z";
|
||||||
|
String actual = localDateToISO.formatUsingJodaTime(localDate);
|
||||||
|
assertEquals(expected, actual);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenLocalDate_whenUsingApacheCommonsLang_thenISOFormat() {
|
||||||
|
LocalDateToISO localDateToISO = new LocalDateToISO();
|
||||||
|
LocalDate localDate = LocalDate.of(2023, 11, 6);
|
||||||
|
|
||||||
|
String expected = "2023-11-06T00:00:00.000Z";
|
||||||
|
String actual = localDateToISO.formatUsingApacheCommonsLang(localDate);
|
||||||
|
assertEquals(expected, actual);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,93 @@
|
||||||
|
package com.baeldung.monthintervalbetweentwodates;
|
||||||
|
|
||||||
|
import org.joda.time.DateTime;
|
||||||
|
import org.joda.time.Months;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.text.ParseException;
|
||||||
|
import java.text.SimpleDateFormat;
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.Period;
|
||||||
|
import java.time.YearMonth;
|
||||||
|
import java.time.temporal.ChronoUnit;
|
||||||
|
import java.util.Date;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
class MonthIntervalUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenTwoDates_whenCalculatingMonthsBetweenUsingJodaTime_thenReturnMonthsDifference() {
|
||||||
|
DateTime firstDate = new DateTime(2023, 5, 25, 0, 0);
|
||||||
|
DateTime secondDate = new DateTime(2023, 11, 23, 0, 0);
|
||||||
|
|
||||||
|
int monthsBetween = Months.monthsBetween(firstDate, secondDate)
|
||||||
|
.getMonths();
|
||||||
|
assertEquals(5, monthsBetween);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenTwoDates_whenCalculatingMonthsBetweenUsingJodaTimeSetTimeToFirstDayOfMonth_thenReturnMonthsDifference() {
|
||||||
|
DateTime firstDate = new DateTime(2023, 5, 25, 0, 0).withDayOfMonth(1);
|
||||||
|
DateTime secondDate = new DateTime(2023, 11, 23, 0, 0).withDayOfMonth(1);
|
||||||
|
|
||||||
|
int monthsBetween = Months.monthsBetween(firstDate, secondDate)
|
||||||
|
.getMonths();
|
||||||
|
assertEquals(6, monthsBetween);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenTwoDates_whenCalculatingMonthsBetweenUsingPeriodClass_thenReturnMonthsDifference() {
|
||||||
|
Period diff = Period.between(LocalDate.parse("2023-05-25"), LocalDate.parse("2023-11-23"));
|
||||||
|
assertEquals(5, diff.getMonths());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenTwoDates_whenCalculatingMonthsBetweenUsingPeriodClassAndAdjsutingDatesToFirstDayOfTheMonth_thenReturnMonthsDifference() {
|
||||||
|
Period diff = Period.between(LocalDate.parse("2023-05-25")
|
||||||
|
.withDayOfMonth(1), LocalDate.parse("2023-11-23")
|
||||||
|
.withDayOfMonth(1));
|
||||||
|
assertEquals(6, diff.getMonths());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenTwoDates_whenCalculatingMonthsBetweenUsingChronoUnitAndYearMonth_thenReturnMonthsDifference() {
|
||||||
|
long diff = ChronoUnit.MONTHS.between(YearMonth.from(LocalDate.parse("2023-05-25")), LocalDate.parse("2023-11-23"));
|
||||||
|
assertEquals(6, diff);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenTwoDates_whenCalculatingMonthsBetweenUsingChronoUnitEnum_thenReturnMonthsDifference() {
|
||||||
|
long monthsBetween = ChronoUnit.MONTHS.between(LocalDate.parse("2023-05-25"), LocalDate.parse("2023-11-23"));
|
||||||
|
assertEquals(5, monthsBetween);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenTwoDates_whenCalculatingMonthsBetweenUsingChronoUnitEnumdSetTimeToFirstDayOfMonth_thenReturnMonthsDifference() {
|
||||||
|
long monthsBetween = ChronoUnit.MONTHS.between(LocalDate.parse("2023-05-25")
|
||||||
|
.withDayOfMonth(1), LocalDate.parse("2023-11-23")
|
||||||
|
.withDayOfMonth(1));
|
||||||
|
assertEquals(6, monthsBetween);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenTwoDates_whenCalculatingMonthsBetweenUsingLegacyDateApi_thenReturnMonthsDifference() throws ParseException {
|
||||||
|
MonthInterval monthDifference = new MonthInterval();
|
||||||
|
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
|
||||||
|
Date startDate = sdf.parse("2016-05-31");
|
||||||
|
Date endDate = sdf.parse("2016-11-30");
|
||||||
|
int monthsBetween = monthDifference.monthsBetween(startDate, endDate);
|
||||||
|
assertEquals(6, monthsBetween);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenTwoDates_whenCalculatingMonthsBetweenUsingLegacyDateApiDayValueConsidered_thenReturnMonthsDifference() throws ParseException {
|
||||||
|
MonthInterval monthDifference = new MonthInterval();
|
||||||
|
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
|
||||||
|
Date startDate = sdf.parse("2016-05-31");
|
||||||
|
Date endDate = sdf.parse("2016-11-28");
|
||||||
|
int monthsBetween = monthDifference.monthsBetweenWithDayValue(startDate, endDate);
|
||||||
|
assertEquals(5, monthsBetween);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,42 @@
|
||||||
|
package com.baeldung.unixtime;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.time.LocalDate;
|
||||||
|
|
||||||
|
import java.time.Month;
|
||||||
|
import java.time.ZoneId;
|
||||||
|
import java.util.Date;
|
||||||
|
|
||||||
|
import org.joda.time.DateTime;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
public class UnixTimeUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTimeUsingDateApi_whenConvertedToUnixTime_thenMatch() {
|
||||||
|
Date date = new Date(2023 - 1900, 1, 15, 0, 0, 0);
|
||||||
|
long expected = 1676419200;
|
||||||
|
long actual = date.getTime() / 1000L;
|
||||||
|
assertEquals(expected, actual);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTimeUsingJodaTime_whenConvertedToUnixTime_thenMatch() {
|
||||||
|
DateTime dateTime = new DateTime(2023, 2, 15, 00, 00, 00, 0);
|
||||||
|
long expected = 1676419200;
|
||||||
|
long actual = dateTime.getMillis() / 1000L;
|
||||||
|
assertEquals(expected, actual);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTimeUsingLocalDate_whenConvertedToUnixTime_thenMatch() {
|
||||||
|
LocalDate date = LocalDate.of(2023, Month.FEBRUARY, 15);
|
||||||
|
Instant instant = date.atStartOfDay().atZone(ZoneId.of("UTC")).toInstant();
|
||||||
|
long expected = 1676419200;
|
||||||
|
long actual = instant.getEpochSecond();
|
||||||
|
assertEquals(expected, actual);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -11,3 +11,4 @@ This module contains articles about arrays conversion in Java
|
||||||
- [Converting an int[] to HashSet in Java](https://www.baeldung.com/java-converting-int-array-to-hashset)
|
- [Converting an int[] to HashSet in Java](https://www.baeldung.com/java-converting-int-array-to-hashset)
|
||||||
- [Convert an ArrayList of String to a String Array in Java](https://www.baeldung.com/java-convert-string-arraylist-array)
|
- [Convert an ArrayList of String to a String Array in Java](https://www.baeldung.com/java-convert-string-arraylist-array)
|
||||||
- [Convert Char Array to Int Array in Java](https://www.baeldung.com/java-convert-char-int-array)
|
- [Convert Char Array to Int Array in Java](https://www.baeldung.com/java-convert-char-int-array)
|
||||||
|
- [How to Convert Byte Array to Char Array](https://www.baeldung.com/java-convert-byte-array-char)
|
||||||
|
|
|
@ -0,0 +1,129 @@
|
||||||
|
package com.baeldung.iteratorvsforloop;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.ConcurrentModificationException;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Iterator;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.ListIterator;
|
||||||
|
|
||||||
|
public class IteratorForLoopUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenEmptyCollection_whenUsingForLoop_thenNoElementsAreIterated() {
|
||||||
|
List<String> names = Collections.emptyList();
|
||||||
|
StringBuilder stringBuilder = new StringBuilder();
|
||||||
|
|
||||||
|
for (int i = 0; i < names.size(); i++) {
|
||||||
|
stringBuilder.append(names.get(i));
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals("", stringBuilder.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenEmptyCollection_whenUsingIterator_thenNoElementsAreIterated() {
|
||||||
|
List<String> names = Collections.emptyList();
|
||||||
|
StringBuilder stringBuilder = new StringBuilder();
|
||||||
|
|
||||||
|
Iterator<String> iterator = names.iterator();
|
||||||
|
while (iterator.hasNext()) {
|
||||||
|
stringBuilder.append(iterator.next());
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals("", stringBuilder.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCollectionWithElements_whenUsingForLoop_thenAllElementsAreIterated() {
|
||||||
|
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
|
||||||
|
StringBuilder stringBuilder = new StringBuilder();
|
||||||
|
|
||||||
|
for (int i = 0; i < names.size(); i++) {
|
||||||
|
stringBuilder.append(names.get(i));
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals("AliceBobCharlie", stringBuilder.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCollectionWithElements_whenUsingIterator_thenAllElementsAreIterated() {
|
||||||
|
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
|
||||||
|
StringBuilder stringBuilder = new StringBuilder();
|
||||||
|
|
||||||
|
Iterator<String> iterator = names.iterator();
|
||||||
|
while (iterator.hasNext()) {
|
||||||
|
stringBuilder.append(iterator.next());
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals("AliceBobCharlie", stringBuilder.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCollectionWithElements_whenUsingForLoop_thenAllElementsAreIteratedReverseOrder() {
|
||||||
|
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
|
||||||
|
StringBuilder stringBuilder = new StringBuilder();
|
||||||
|
|
||||||
|
for (int i = names.size() - 1; i >= 0; i--) {
|
||||||
|
stringBuilder.append(names.get(i));
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals("CharlieBobAlice", stringBuilder.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCollectionWithElements_whenUsingListIterator_thenAllElementsAreIteratedInReverseOrder() {
|
||||||
|
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
|
||||||
|
StringBuilder stringBuilder = new StringBuilder();
|
||||||
|
|
||||||
|
ListIterator<String> listIterator = names.listIterator(names.size());
|
||||||
|
while (listIterator.hasPrevious()) {
|
||||||
|
stringBuilder.append(listIterator.previous());
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals("CharlieBobAlice", stringBuilder.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCollectionWithElements_whenRemovingElementDuringForLoopIteration_thenConcurrentModificationExceptionIsThrown() {
|
||||||
|
List<String> names = new ArrayList<>(List.of("Alice", "Bob", "Charlie"));
|
||||||
|
|
||||||
|
assertThrows(ConcurrentModificationException.class, () -> {
|
||||||
|
for (String name : names) {
|
||||||
|
names.remove("Bob");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCollectionWithElements_whenRemovingElementUsingIterator_thenElementIsRemovedSafely() {
|
||||||
|
List<String> names = new ArrayList<>(Arrays.asList("Alice", "Bob", "Charlie"));
|
||||||
|
Iterator<String> iterator = names.iterator();
|
||||||
|
|
||||||
|
while (iterator.hasNext()) {
|
||||||
|
String name = iterator.next();
|
||||||
|
if (name.equals("Bob")) {
|
||||||
|
iterator.remove();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
List<String> expected = Arrays.asList("Alice", "Charlie");
|
||||||
|
assertIterableEquals(expected, names);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCollectionWithElements_whenModifyingElementToLowerCaseDuringForLoopIteration_thenElementsAreModifiedToLowerCase() {
|
||||||
|
List<String> names = new ArrayList<>(List.of("Alice", "Bob", "Charlie"));
|
||||||
|
|
||||||
|
for (int i = 0; i < names.size(); i++) {
|
||||||
|
names.set(i, names.get(i).toLowerCase());
|
||||||
|
}
|
||||||
|
|
||||||
|
List<String> expected = Arrays.asList("alice","bob", "charlie");
|
||||||
|
assertIterableEquals(expected, names);
|
||||||
|
}
|
||||||
|
}
|
|
@ -43,7 +43,6 @@
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<vavr.version>0.10.3</vavr.version>
|
<vavr.version>0.10.3</vavr.version>
|
||||||
<java.version>11</java.version>
|
|
||||||
<modelmapper.version>3.2.0</modelmapper.version>
|
<modelmapper.version>3.2.0</modelmapper.version>
|
||||||
</properties>
|
</properties>
|
||||||
</project>
|
</project>
|
|
@ -39,7 +39,7 @@
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.projectlombok</groupId>
|
<groupId>org.projectlombok</groupId>
|
||||||
<artifactId>lombok</artifactId>
|
<artifactId>lombok</artifactId>
|
||||||
<version>1.18.26</version>
|
<version>${lombok.version}</version>
|
||||||
<scope>provided</scope>
|
<scope>provided</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
|
@ -67,7 +67,7 @@
|
||||||
<jmh.version>1.21</jmh.version>
|
<jmh.version>1.21</jmh.version>
|
||||||
<commons-lang.version>2.2</commons-lang.version>
|
<commons-lang.version>2.2</commons-lang.version>
|
||||||
<gson.version>2.10.1</gson.version>
|
<gson.version>2.10.1</gson.version>
|
||||||
<jackson.version>2.15.2</jackson.version>
|
<jackson.version>2.16.0</jackson.version>
|
||||||
<org.json.version>20230618</org.json.version>
|
<org.json.version>20230618</org.json.version>
|
||||||
</properties>
|
</properties>
|
||||||
</project>
|
</project>
|
|
@ -13,4 +13,20 @@
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.google.guava</groupId>
|
||||||
|
<artifactId>guava</artifactId>
|
||||||
|
<version>${guava.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.vavr</groupId>
|
||||||
|
<artifactId>vavr</artifactId>
|
||||||
|
<version>${vavr.version}</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<vavr.version>0.10.4</vavr.version>
|
||||||
|
</properties>
|
||||||
</project>
|
</project>
|
|
@ -0,0 +1,52 @@
|
||||||
|
package com.baeldung.sorting;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
import com.google.common.collect.Ordering;
|
||||||
|
|
||||||
|
public class SortingBasedOnAnotherList {
|
||||||
|
static List<String> sortUsingForLoop(List<String> listToSort, List<String> listWithOrder) {
|
||||||
|
List<String> sortedList = new ArrayList<>();
|
||||||
|
for(String element: listWithOrder) {
|
||||||
|
if(listToSort.contains(element)) {
|
||||||
|
sortedList.add(element);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return sortedList;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void sortUsingComparator(List<String> listToSort, List<String> listWithOrder) {
|
||||||
|
listToSort.sort(Comparator.comparingInt(listWithOrder::indexOf));
|
||||||
|
}
|
||||||
|
|
||||||
|
static void sortUsingStreamAPI(List<String> listToSort, List<String> listWithOrder) {
|
||||||
|
Map<String,Integer> indicesMap = listWithOrder.stream().collect(Collectors.toMap(e->e, listWithOrder::indexOf));
|
||||||
|
listToSort.sort(Comparator.comparingInt(indicesMap::get));
|
||||||
|
}
|
||||||
|
|
||||||
|
static void sortUsingMap(List<String> listToSort, List<String> listWithOrder) {
|
||||||
|
Map<String, Integer> orderedIndicesMap = new HashMap<>();
|
||||||
|
for(int i = 0; i < listWithOrder.size(); i++) {
|
||||||
|
orderedIndicesMap.put(listWithOrder.get(i), i);
|
||||||
|
}
|
||||||
|
listToSort.sort(Comparator.comparingInt(orderedIndicesMap::get));
|
||||||
|
}
|
||||||
|
|
||||||
|
static List<String> sortUsingGuava(List<String> listToSort, List<String> listWithOrder) {
|
||||||
|
Ordering<String> explicitOrdering = Ordering.explicit(listWithOrder);
|
||||||
|
List<String> sortedList = explicitOrdering.sortedCopy(listToSort);
|
||||||
|
return sortedList;
|
||||||
|
}
|
||||||
|
|
||||||
|
static List<String> sortUsingVavr(List<String> listToSort, List<String> listWithOrder) {
|
||||||
|
io.vavr.collection.List<String> listWithOrderedElements = io.vavr.collection.List.ofAll(listWithOrder);
|
||||||
|
io.vavr.collection.List<String> listToSortElements = io.vavr.collection.List.ofAll(listToSort);
|
||||||
|
io.vavr.collection.List<String> sortedList = listToSortElements.sortBy(listWithOrderedElements::indexOf);
|
||||||
|
return sortedList.asJava();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,70 @@
|
||||||
|
package com.baeldung.sorting;
|
||||||
|
|
||||||
|
import static com.baeldung.sorting.SortingBasedOnAnotherList.sortUsingComparator;
|
||||||
|
import static com.baeldung.sorting.SortingBasedOnAnotherList.sortUsingForLoop;
|
||||||
|
import static com.baeldung.sorting.SortingBasedOnAnotherList.sortUsingGuava;
|
||||||
|
import static com.baeldung.sorting.SortingBasedOnAnotherList.sortUsingMap;
|
||||||
|
import static com.baeldung.sorting.SortingBasedOnAnotherList.sortUsingStreamAPI;
|
||||||
|
import static com.baeldung.sorting.SortingBasedOnAnotherList.sortUsingVavr;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
public class SortingBasedOnAnotherListUnitTest {
|
||||||
|
@Test
|
||||||
|
public void givenTwoList_whenUsingForLoop_thenSort() {
|
||||||
|
List<String> listWithOrder = Arrays.asList("Burger", "Coke", "Fries", "Pizza");
|
||||||
|
List<String> listToSort = Arrays.asList("Pizza", "Burger", "Fries", "Coke");
|
||||||
|
sortUsingForLoop(listToSort, listWithOrder);
|
||||||
|
List<String> expectedSortedList = Arrays.asList("Burger", "Coke", "Fries", "Pizza");
|
||||||
|
assertEquals(expectedSortedList, listWithOrder);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoList_whenUsingComparator_thenSort() {
|
||||||
|
List<String> listWithOrder = Arrays.asList("Burger", "Coke", "Fries", "Pizza");
|
||||||
|
List<String> listToSort = Arrays.asList("Pizza", "Burger", "Fries", "Coke");
|
||||||
|
sortUsingComparator(listToSort, listWithOrder);
|
||||||
|
List<String> expectedSortedList = Arrays.asList("Burger", "Coke", "Fries", "Pizza");
|
||||||
|
assertEquals(expectedSortedList, listToSort);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoList_whenUsingStreamAPI_thenSort() {
|
||||||
|
List<String> listWithOrder = Arrays.asList("Burger", "Coke", "Fries", "Pizza");
|
||||||
|
List<String> listToSort = Arrays.asList("Pizza", "Burger", "Fries", "Coke");
|
||||||
|
sortUsingStreamAPI(listToSort, listWithOrder);
|
||||||
|
List<String> expectedSortedList = Arrays.asList("Burger", "Coke", "Fries", "Pizza");
|
||||||
|
assertEquals(expectedSortedList, listToSort);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoList_whenUsingMap_thenSort() {
|
||||||
|
List<String> listWithOrder = Arrays.asList("Burger", "Coke", "Fries", "Pizza");
|
||||||
|
List<String> listToSort = Arrays.asList("Pizza", "Burger", "Fries", "Coke");
|
||||||
|
sortUsingMap(listToSort, listWithOrder);
|
||||||
|
List<String> expectedSortedList = Arrays.asList("Burger", "Coke", "Fries", "Pizza");
|
||||||
|
assertEquals(expectedSortedList, listToSort);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoList_whenUsingGuavaExplicit_thenSort() {
|
||||||
|
List<String> listWithOrder = Arrays.asList("Burger", "Coke", "Fries", "Pizza");
|
||||||
|
List<String> listToSort = Arrays.asList("Pizza", "Burger", "Fries", "Coke");
|
||||||
|
sortUsingGuava(listToSort, listWithOrder);
|
||||||
|
List<String> expectedSortedList = Arrays.asList("Burger", "Coke", "Fries", "Pizza");
|
||||||
|
assertEquals(expectedSortedList, listWithOrder);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoList_whenUsingVavr_thenSort() {
|
||||||
|
List<String> listWithOrder = Arrays.asList("Burger", "Coke", "Fries", "Pizza");
|
||||||
|
List<String> listToSort = Arrays.asList("Pizza", "Burger", "Fries", "Coke");
|
||||||
|
sortUsingVavr(listToSort, listWithOrder);
|
||||||
|
List<String> expectedSortedList = Arrays.asList("Burger", "Coke", "Fries", "Pizza");
|
||||||
|
assertEquals(expectedSortedList, listWithOrder);
|
||||||
|
}
|
||||||
|
}
|
|
@ -10,4 +10,5 @@ This module contains articles about Map data structures in Java.
|
||||||
- [Java HashMap Load Factor](https://www.baeldung.com/java-hashmap-load-factor)
|
- [Java HashMap Load Factor](https://www.baeldung.com/java-hashmap-load-factor)
|
||||||
- [Converting Java Properties to HashMap](https://www.baeldung.com/java-convert-properties-to-hashmap)
|
- [Converting Java Properties to HashMap](https://www.baeldung.com/java-convert-properties-to-hashmap)
|
||||||
- [Get Values and Keys as ArrayList From a HashMap](https://www.baeldung.com/java-values-keys-arraylists-hashmap)
|
- [Get Values and Keys as ArrayList From a HashMap](https://www.baeldung.com/java-values-keys-arraylists-hashmap)
|
||||||
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-2)
|
- [Remove Duplicate Values From HashMap in Java](https://www.baeldung.com/java-hashmap-delete-duplicates)
|
||||||
|
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-2)[[next -->]](/core-java-modules/core-java-collections-maps-4)
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.map.removeuplicate;
|
package com.baeldung.map.removeduplicate;
|
||||||
|
|
||||||
import static java.util.stream.Collectors.toMap;
|
import static java.util.stream.Collectors.toMap;
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
|
@ -9,3 +9,4 @@ This module contains articles about Map data structures in Java.
|
||||||
- [Difference Between Map and HashMap in Java](https://www.baeldung.com/java-map-vs-hashmap)
|
- [Difference Between Map and HashMap in Java](https://www.baeldung.com/java-map-vs-hashmap)
|
||||||
- [How to Create a New Entry in a Map](https://www.baeldung.com/java-map-new-entry)
|
- [How to Create a New Entry in a Map](https://www.baeldung.com/java-map-new-entry)
|
||||||
- [Difference Between Map and MultivaluedMap in Java](https://www.baeldung.com/java-map-vs-multivaluedmap)
|
- [Difference Between Map and MultivaluedMap in Java](https://www.baeldung.com/java-map-vs-multivaluedmap)
|
||||||
|
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-3)[[next -->]](/core-java-modules/core-java-collections-maps-5)
|
||||||
|
|
|
@ -10,4 +10,5 @@
|
||||||
- [How to Invert a Map in Java](https://www.baeldung.com/java-invert-map)
|
- [How to Invert a Map in Java](https://www.baeldung.com/java-invert-map)
|
||||||
- [Implementing a Map with Multiple Keys in Java](https://www.baeldung.com/java-multiple-keys-map)
|
- [Implementing a Map with Multiple Keys in Java](https://www.baeldung.com/java-multiple-keys-map)
|
||||||
- [Difference Between Map.ofEntries() and Map.of()](https://www.baeldung.com/map-ofentries-and-map-of)
|
- [Difference Between Map.ofEntries() and Map.of()](https://www.baeldung.com/map-ofentries-and-map-of)
|
||||||
- More articles: [[<-- prev]](../core-java-collections-maps-4)
|
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-4)[[next -->]](/core-java-modules/core-java-collections-maps-6)
|
||||||
|
|
||||||
|
|
|
@ -7,6 +7,7 @@
|
||||||
- [Converting JsonNode Object to Map](https://www.baeldung.com/jackson-jsonnode-map)
|
- [Converting JsonNode Object to Map](https://www.baeldung.com/jackson-jsonnode-map)
|
||||||
- [How to Modify a Key in a HashMap?](https://www.baeldung.com/java-hashmap-modify-key)
|
- [How to Modify a Key in a HashMap?](https://www.baeldung.com/java-hashmap-modify-key)
|
||||||
- [Converting String or String Array to Map in Java](https://www.baeldung.com/java-convert-string-to-map)
|
- [Converting String or String Array to Map in Java](https://www.baeldung.com/java-convert-string-to-map)
|
||||||
- [Remove Duplicate Values From HashMap in Java](https://www.baeldung.com/java-hashmap-delete-duplicates)
|
|
||||||
- [Sorting Java Map in Descending Order](https://www.baeldung.com/java-sort-map-descending)
|
- [Sorting Java Map in Descending Order](https://www.baeldung.com/java-sort-map-descending)
|
||||||
- [Convert HashMap.toString() to HashMap in Java](https://www.baeldung.com/hashmap-from-tostring)
|
- [Convert HashMap.toString() to HashMap in Java](https://www.baeldung.com/hashmap-from-tostring)
|
||||||
|
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-5)[[next -->]](/core-java-modules/core-java-collections-maps-7)
|
||||||
|
|
||||||
|
|
|
@ -13,14 +13,11 @@
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<properties>
|
|
||||||
<spring.version>5.2.5.RELEASE</spring.version>
|
|
||||||
</properties>
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.fasterxml.jackson.core</groupId>
|
<groupId>com.fasterxml.jackson.core</groupId>
|
||||||
<artifactId>jackson-databind</artifactId>
|
<artifactId>jackson-databind</artifactId>
|
||||||
<version>2.13.1</version>
|
<version>2.16.0</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.openjdk.jmh</groupId>
|
<groupId>org.openjdk.jmh</groupId>
|
||||||
|
@ -40,7 +37,7 @@
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>junit</groupId>
|
<groupId>junit</groupId>
|
||||||
<artifactId>junit</artifactId>
|
<artifactId>junit</artifactId>
|
||||||
<version>4.13.1</version>
|
<version>${junit.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
|
@ -51,4 +48,8 @@
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<spring.version>5.2.5.RELEASE</spring.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
|
@ -4,5 +4,7 @@
|
||||||
- [How to Write Hashmap to CSV File](https://www.baeldung.com/java-write-hashmap-csv)
|
- [How to Write Hashmap to CSV File](https://www.baeldung.com/java-write-hashmap-csv)
|
||||||
- [How to Get First or Last Entry From a LinkedHashMap in Java](https://www.baeldung.com/java-linkedhashmap-first-last-key-value-pair)
|
- [How to Get First or Last Entry From a LinkedHashMap in Java](https://www.baeldung.com/java-linkedhashmap-first-last-key-value-pair)
|
||||||
- [How to Write and Read a File with a Java HashMap](https://www.baeldung.com/java-hashmap-write-read-file)
|
- [How to Write and Read a File with a Java HashMap](https://www.baeldung.com/java-hashmap-write-read-file)
|
||||||
- [Limiting the Max Size of a HashMap in Java](https://www.baeldung.com/java-hashmap-max-size)
|
- [Limiting the Max Size of a HashMap in Java](https://www.baeldung.com/java-hashmap-size-bound)
|
||||||
|
- [How to Sort LinkedHashMap By Values in Java](https://www.baeldung.com/java-sort-linkedhashmap-using-values)
|
||||||
|
- [How to Increment a Map Value in Java](https://www.baeldung.com/java-increment-map-value)
|
||||||
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-6)
|
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-6)
|
|
@ -1,15 +1,11 @@
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
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>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<artifactId>core-java-collections-maps-7</artifactId>
|
<artifactId>core-java-collections-maps-7</artifactId>
|
||||||
<name>core-java-collections-maps-7</name>
|
<name>core-java-collections-maps-7</name>
|
||||||
<packaging>jar</packaging>
|
<packaging>jar</packaging>
|
||||||
<properties>
|
|
||||||
<gson.version>2.10.1</gson.version>
|
|
||||||
<csv.version>1.5</csv.version>
|
|
||||||
</properties>
|
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<artifactId>core-java-modules</artifactId>
|
<artifactId>core-java-modules</artifactId>
|
||||||
|
@ -63,4 +59,10 @@
|
||||||
</plugin>
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<gson.version>2.10.1</gson.version>
|
||||||
|
<csv.version>1.5</csv.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
|
|
@ -7,3 +7,4 @@
|
||||||
- [Testing Multi-Threaded Code in Java](https://www.baeldung.com/java-testing-multithreaded)
|
- [Testing Multi-Threaded Code in Java](https://www.baeldung.com/java-testing-multithreaded)
|
||||||
- [How to Check if All Runnables Are Done](https://www.baeldung.com/java-runnables-check-status)
|
- [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)
|
- [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)
|
||||||
|
|
|
@ -0,0 +1,150 @@
|
||||||
|
package com.baeldung.concurrent.completablefuture;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
import java.util.concurrent.CompletionException;
|
||||||
|
import java.util.concurrent.ExecutionException;
|
||||||
|
import java.util.concurrent.Executor;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.concurrent.TimeoutException;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class CompletableFutureUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAsyncTask_whenProcessingAsyncSucceed_thenReturnSuccess() throws ExecutionException, InterruptedException {
|
||||||
|
Microservice mockMicroserviceA = mock(Microservice.class);
|
||||||
|
Microservice mockMicroserviceB = mock(Microservice.class);
|
||||||
|
|
||||||
|
when(mockMicroserviceA.retrieveAsync(any())).thenReturn(CompletableFuture.completedFuture("Hello"));
|
||||||
|
when(mockMicroserviceB.retrieveAsync(any())).thenReturn(CompletableFuture.completedFuture("World"));
|
||||||
|
|
||||||
|
CompletableFuture<String> resultFuture = processAsync(List.of(mockMicroserviceA, mockMicroserviceB));
|
||||||
|
|
||||||
|
String result = resultFuture.get();
|
||||||
|
assertEquals("HelloWorld", result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAsyncTask_whenProcessingAsyncWithException_thenReturnException() throws ExecutionException, InterruptedException {
|
||||||
|
Microservice mockMicroserviceA = mock(Microservice.class);
|
||||||
|
Microservice mockMicroserviceB = mock(Microservice.class);
|
||||||
|
|
||||||
|
when(mockMicroserviceA.retrieveAsync(any())).thenReturn(CompletableFuture.completedFuture("Hello"));
|
||||||
|
when(mockMicroserviceB.retrieveAsync(any())).thenReturn(CompletableFuture.failedFuture(new RuntimeException("Simulated Exception")));
|
||||||
|
CompletableFuture<String> resultFuture = processAsync(List.of(mockMicroserviceA, mockMicroserviceB));
|
||||||
|
// Use assertThrows to verify that the expected exception is thrown
|
||||||
|
ExecutionException exception = assertThrows(ExecutionException.class, resultFuture::get);
|
||||||
|
// Assert the exception message
|
||||||
|
assertEquals("Simulated Exception", exception.getCause()
|
||||||
|
.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAsyncTask_whenProcessingAsyncWithTimeout_thenHandleTimeoutException() throws ExecutionException, InterruptedException {
|
||||||
|
Microservice mockMicroserviceA = mock(Microservice.class);
|
||||||
|
Microservice mockMicroserviceB = mock(Microservice.class);
|
||||||
|
Executor delayedExecutor = CompletableFuture.delayedExecutor(200, TimeUnit.MILLISECONDS);
|
||||||
|
when(mockMicroserviceA.retrieveAsync(any())).thenReturn(CompletableFuture.supplyAsync(() -> "Hello", delayedExecutor));
|
||||||
|
Executor delayedExecutor2 = CompletableFuture.delayedExecutor(500, TimeUnit.MILLISECONDS);
|
||||||
|
when(mockMicroserviceB.retrieveAsync(any())).thenReturn(CompletableFuture.supplyAsync(() -> "World", delayedExecutor2));
|
||||||
|
CompletableFuture<String> resultFuture = processAsync(List.of(mockMicroserviceA, mockMicroserviceB));
|
||||||
|
assertThrows(TimeoutException.class, () -> resultFuture.get(300, TimeUnit.MILLISECONDS));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCompletableFuture_whenCompleted_thenStateIsDone() {
|
||||||
|
Executor delayedExecutor = CompletableFuture.delayedExecutor(200, TimeUnit.MILLISECONDS);
|
||||||
|
CompletableFuture<String> cf1 = CompletableFuture.supplyAsync(() -> "Hello", delayedExecutor);
|
||||||
|
CompletableFuture<String> cf2 = CompletableFuture.supplyAsync(() -> " World");
|
||||||
|
CompletableFuture<String> cf3 = CompletableFuture.supplyAsync(() -> "!");
|
||||||
|
CompletableFuture<String>[] cfs = new CompletableFuture[] { cf1, cf2, cf3 };
|
||||||
|
|
||||||
|
CompletableFuture<Void> allCf = CompletableFuture.allOf(cfs);
|
||||||
|
|
||||||
|
assertFalse(allCf.isDone());
|
||||||
|
allCf.join();
|
||||||
|
String result = Arrays.stream(cfs)
|
||||||
|
.map(CompletableFuture::join)
|
||||||
|
.collect(Collectors.joining());
|
||||||
|
|
||||||
|
assertFalse(allCf.isCancelled());
|
||||||
|
assertTrue(allCf.isDone());
|
||||||
|
assertFalse(allCf.isCompletedExceptionally());
|
||||||
|
assertEquals(result, "Hello World!");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCompletableFuture_whenCompletedWithException_thenStateIsCompletedExceptionally() throws ExecutionException, InterruptedException {
|
||||||
|
Executor delayedExecutor = CompletableFuture.delayedExecutor(200, TimeUnit.MILLISECONDS);
|
||||||
|
CompletableFuture<String> cf1 = CompletableFuture.supplyAsync(() -> "Hello", delayedExecutor);
|
||||||
|
CompletableFuture<String> cf2 = CompletableFuture.failedFuture(new RuntimeException("Simulated Exception"));
|
||||||
|
CompletableFuture<String> cf3 = CompletableFuture.supplyAsync(() -> "!");
|
||||||
|
CompletableFuture<String>[] cfs = new CompletableFuture[] { cf1, cf2, cf3 };
|
||||||
|
|
||||||
|
CompletableFuture<Void> allCf = CompletableFuture.allOf(cfs);
|
||||||
|
|
||||||
|
assertFalse(allCf.isDone());
|
||||||
|
assertFalse(allCf.isCompletedExceptionally());
|
||||||
|
|
||||||
|
// Exception is expected, assert the cause
|
||||||
|
CompletionException exception = assertThrows(CompletionException.class, allCf::join);
|
||||||
|
|
||||||
|
assertEquals("Simulated Exception", exception.getCause()
|
||||||
|
.getMessage());
|
||||||
|
assertTrue(allCf.isCompletedExceptionally());
|
||||||
|
assertTrue(allCf.isDone());
|
||||||
|
assertFalse(allCf.isCancelled());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCompletableFuture_whenCancelled_thenStateIsCancelled() throws ExecutionException, InterruptedException {
|
||||||
|
Executor delayedExecutor = CompletableFuture.delayedExecutor(200, TimeUnit.MILLISECONDS);
|
||||||
|
CompletableFuture<String> cf1 = CompletableFuture.supplyAsync(() -> "Hello", delayedExecutor);
|
||||||
|
CompletableFuture<String> cf2 = CompletableFuture.supplyAsync(() -> " World");
|
||||||
|
CompletableFuture<String> cf3 = CompletableFuture.supplyAsync(() -> "!");
|
||||||
|
CompletableFuture<String>[] cfs = new CompletableFuture[] { cf1, cf2, cf3 };
|
||||||
|
CompletableFuture<Void> allCf = CompletableFuture.allOf(cfs);
|
||||||
|
assertFalse(allCf.isDone());
|
||||||
|
assertFalse(allCf.isCompletedExceptionally());
|
||||||
|
allCf.cancel(true);
|
||||||
|
assertTrue(allCf.isCancelled());
|
||||||
|
assertTrue(allCf.isDone());
|
||||||
|
}
|
||||||
|
|
||||||
|
CompletableFuture<String> processAsync(List<Microservice> microservices) {
|
||||||
|
List<CompletableFuture<String>> dataFetchFutures = fetchDataAsync(microservices);
|
||||||
|
return combineResults(dataFetchFutures);
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<CompletableFuture<String>> fetchDataAsync(List<Microservice> microservices) {
|
||||||
|
return microservices.stream()
|
||||||
|
.map(client -> client.retrieveAsync(""))
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
private CompletableFuture<String> combineResults(List<CompletableFuture<String>> dataFetchFutures) {
|
||||||
|
return CompletableFuture.allOf(dataFetchFutures.toArray(new CompletableFuture[0]))
|
||||||
|
.thenApply(v -> dataFetchFutures.stream()
|
||||||
|
.map(future -> future.exceptionally(ex -> {
|
||||||
|
throw new CompletionException(ex);
|
||||||
|
})
|
||||||
|
.join())
|
||||||
|
.collect(Collectors.joining()));
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Microservice {
|
||||||
|
CompletableFuture<String> retrieveAsync(String input);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,30 @@
|
||||||
|
package com.baeldung.callback.completablefuture;
|
||||||
|
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
|
||||||
|
public class CompletableFutureCallbackExample {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
CompletableFuture<String> completableFuture = new CompletableFuture<>();
|
||||||
|
Runnable runnable = downloadFile(completableFuture);
|
||||||
|
completableFuture.whenComplete((res, error) -> {
|
||||||
|
if (error != null) {
|
||||||
|
// handle the exception scenario
|
||||||
|
} else if (res != null) {
|
||||||
|
// send data to DB
|
||||||
|
}
|
||||||
|
});
|
||||||
|
new Thread(runnable).start();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Runnable downloadFile(CompletableFuture<String> completableFuture) {
|
||||||
|
return () -> {
|
||||||
|
try {
|
||||||
|
//logic to download file
|
||||||
|
Thread.sleep(5000);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
completableFuture.complete("pic.jpg");
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,42 @@
|
||||||
|
package com.baeldung.callback.listenablefuture;
|
||||||
|
|
||||||
|
import java.util.concurrent.Callable;
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
|
||||||
|
import com.google.common.util.concurrent.FutureCallback;
|
||||||
|
import com.google.common.util.concurrent.Futures;
|
||||||
|
import com.google.common.util.concurrent.ListenableFuture;
|
||||||
|
import com.google.common.util.concurrent.ListeningExecutorService;
|
||||||
|
import com.google.common.util.concurrent.MoreExecutors;
|
||||||
|
|
||||||
|
|
||||||
|
public class ListenableFutureCallbackExample {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
|
||||||
|
ExecutorService executorService = Executors.newFixedThreadPool(1);
|
||||||
|
ListeningExecutorService pool = MoreExecutors.listeningDecorator(executorService);
|
||||||
|
ListenableFuture<String> listenableFuture = pool.submit(downloadFile());
|
||||||
|
|
||||||
|
Futures.addCallback(listenableFuture, new FutureCallback<String>() {
|
||||||
|
@Override
|
||||||
|
public void onSuccess(String result) {
|
||||||
|
// code to push fileName to DB
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onFailure(Throwable throwable) {
|
||||||
|
// code to take appropriate action when there is an error
|
||||||
|
}
|
||||||
|
}, executorService);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Callable<String> downloadFile() {
|
||||||
|
return () -> {
|
||||||
|
// Mimicking the downloading of a file by adding a sleep call
|
||||||
|
Thread.sleep(5000);
|
||||||
|
return "pic.jpg";
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,24 @@
|
||||||
|
package com.baeldung.concurrent.executorservice;
|
||||||
|
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
|
||||||
|
public class ExecuteExample {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
ExecutorService executorService = Executors.newFixedThreadPool(2);
|
||||||
|
// Task using Runnable
|
||||||
|
Runnable task = () -> {
|
||||||
|
int[] numbers = { 1, 2, 3, 4, 5 };
|
||||||
|
int sum = 0;
|
||||||
|
for (int num : numbers) {
|
||||||
|
sum += num;
|
||||||
|
}
|
||||||
|
System.out.println("Sum calculated using execute:" + sum);
|
||||||
|
};
|
||||||
|
// Submit the task using execute
|
||||||
|
executorService.execute(task);
|
||||||
|
executorService.shutdown();
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,31 @@
|
||||||
|
package com.baeldung.concurrent.executorservice;
|
||||||
|
|
||||||
|
import java.util.concurrent.Callable;
|
||||||
|
import java.util.concurrent.ExecutionException;
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.Future;
|
||||||
|
|
||||||
|
public class SubmitExample {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
ExecutorService executorService = Executors.newFixedThreadPool(2);
|
||||||
|
Callable<Integer> task = () -> {
|
||||||
|
int[] numbers = { 1, 2, 3, 4, 5 };
|
||||||
|
int sum = 0;
|
||||||
|
for (int num : numbers) {
|
||||||
|
sum += num;
|
||||||
|
}
|
||||||
|
return sum;
|
||||||
|
};
|
||||||
|
// Submit the task and obtain a Future
|
||||||
|
Future<Integer> result = executorService.submit(task);
|
||||||
|
try {
|
||||||
|
// Get the result
|
||||||
|
int sum = result.get();
|
||||||
|
System.out.println("Sum calculated using submit:" + sum);
|
||||||
|
} catch (InterruptedException | ExecutionException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
executorService.shutdown();
|
||||||
|
}
|
||||||
|
}
|
|
@ -11,3 +11,4 @@ This module contains articles about converting between Java date and time object
|
||||||
- [Conversion From 12-Hour Time to 24-Hour Time in Java](https://www.baeldung.com/java-convert-time-format)
|
- [Conversion From 12-Hour Time to 24-Hour Time in Java](https://www.baeldung.com/java-convert-time-format)
|
||||||
- [Convert Epoch Time to LocalDate and LocalDateTime](https://www.baeldung.com/java-convert-epoch-localdate)
|
- [Convert Epoch Time to LocalDate and LocalDateTime](https://www.baeldung.com/java-convert-epoch-localdate)
|
||||||
- [Convert Timestamp String to Long in Java](https://www.baeldung.com/java-convert-timestamp-string-long)
|
- [Convert Timestamp String to Long in Java](https://www.baeldung.com/java-convert-timestamp-string-long)
|
||||||
|
- [Convert Long Timestamp to LocalDateTime in Java](https://www.baeldung.com/java-convert-long-timestamp-localdatetime)
|
||||||
|
|
|
@ -0,0 +1,16 @@
|
||||||
|
package com.baeldung.lazylambda;
|
||||||
|
|
||||||
|
import java.util.function.Supplier;
|
||||||
|
|
||||||
|
public class LambdaSupplier<T> {
|
||||||
|
|
||||||
|
protected final Supplier<T> expensiveData;
|
||||||
|
|
||||||
|
public LambdaSupplier(Supplier<T> expensiveData) {
|
||||||
|
this.expensiveData = expensiveData;
|
||||||
|
}
|
||||||
|
|
||||||
|
public T getData() {
|
||||||
|
return expensiveData.get();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,21 @@
|
||||||
|
package com.baeldung.lazylambda;
|
||||||
|
|
||||||
|
import java.util.function.Supplier;
|
||||||
|
|
||||||
|
public class LazyLambdaSupplier<T> extends LambdaSupplier<T> {
|
||||||
|
|
||||||
|
private T data;
|
||||||
|
|
||||||
|
public LazyLambdaSupplier(Supplier<T> expensiveData) {
|
||||||
|
super(expensiveData);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public T getData() {
|
||||||
|
if (data != null) {
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
return data = expensiveData.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,26 @@
|
||||||
|
package com.baeldung.lazylambda;
|
||||||
|
|
||||||
|
import java.util.concurrent.atomic.AtomicReference;
|
||||||
|
import java.util.function.Supplier;
|
||||||
|
|
||||||
|
public class LazyLambdaThreadSafeSupplier<T> extends LambdaSupplier<T> {
|
||||||
|
|
||||||
|
private final AtomicReference<T> data;
|
||||||
|
|
||||||
|
public LazyLambdaThreadSafeSupplier(Supplier<T> expensiveData) {
|
||||||
|
super(expensiveData);
|
||||||
|
data = new AtomicReference<>();
|
||||||
|
}
|
||||||
|
|
||||||
|
public T getData() {
|
||||||
|
if (data.get() == null) {
|
||||||
|
synchronized (data) {
|
||||||
|
if (data.get() == null) {
|
||||||
|
data.set(expensiveData.get());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return data.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,24 @@
|
||||||
|
package com.baeldung.lazylambda;
|
||||||
|
|
||||||
|
import java.util.function.Supplier;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.mockito.Mockito;
|
||||||
|
|
||||||
|
public class LambdaSupplierUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCalledMultipleTimes_thenShouldBeCalledMultipleTimes() {
|
||||||
|
@SuppressWarnings("unchecked") Supplier<String> mockedExpensiveFunction = Mockito.mock(Supplier.class);
|
||||||
|
Mockito.when(mockedExpensiveFunction.get())
|
||||||
|
.thenReturn("expensive call");
|
||||||
|
LambdaSupplier<String> testee = new LambdaSupplier<>(mockedExpensiveFunction);
|
||||||
|
Mockito.verify(mockedExpensiveFunction, Mockito.never())
|
||||||
|
.get();
|
||||||
|
testee.getData();
|
||||||
|
testee.getData();
|
||||||
|
Mockito.verify(mockedExpensiveFunction, Mockito.times(2))
|
||||||
|
.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,51 @@
|
||||||
|
package com.baeldung.lazylambda;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.function.Supplier;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.mockito.Mockito;
|
||||||
|
import org.mockito.stubbing.Answer;
|
||||||
|
|
||||||
|
public class LazyLambdaSupplierUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCalledMultipleTimes_thenShouldBeCalledOnlyOnce() {
|
||||||
|
@SuppressWarnings("unchecked") Supplier<String> mockedExpensiveFunction = Mockito.mock(Supplier.class);
|
||||||
|
Mockito.when(mockedExpensiveFunction.get())
|
||||||
|
.thenReturn("expensive call");
|
||||||
|
LazyLambdaSupplier<String> testee = new LazyLambdaSupplier<>(mockedExpensiveFunction);
|
||||||
|
Mockito.verify(mockedExpensiveFunction, Mockito.never())
|
||||||
|
.get();
|
||||||
|
testee.getData();
|
||||||
|
testee.getData();
|
||||||
|
Mockito.verify(mockedExpensiveFunction, Mockito.times(1))
|
||||||
|
.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCalledMultipleTimesConcurrently_thenShouldBeCalledMultipleTimes() throws InterruptedException {
|
||||||
|
@SuppressWarnings("unchecked") Supplier<String> mockedExpensiveFunction = Mockito.mock(Supplier.class);
|
||||||
|
Mockito.when(mockedExpensiveFunction.get())
|
||||||
|
.thenAnswer((Answer<String>) invocation -> {
|
||||||
|
Thread.sleep(1000L);
|
||||||
|
return "Late response!";
|
||||||
|
});
|
||||||
|
LazyLambdaSupplier<String> testee = new LazyLambdaSupplier<>(mockedExpensiveFunction);
|
||||||
|
Mockito.verify(mockedExpensiveFunction, Mockito.never())
|
||||||
|
.get();
|
||||||
|
|
||||||
|
ExecutorService executorService = Executors.newFixedThreadPool(4);
|
||||||
|
executorService.invokeAll(List.of(testee::getData, testee::getData));
|
||||||
|
executorService.shutdown();
|
||||||
|
if (!executorService.awaitTermination(5, TimeUnit.SECONDS)) {
|
||||||
|
executorService.shutdownNow();
|
||||||
|
}
|
||||||
|
|
||||||
|
Mockito.verify(mockedExpensiveFunction, Mockito.times(2))
|
||||||
|
.get();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,52 @@
|
||||||
|
package com.baeldung.lazylambda;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.function.Supplier;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.mockito.Mockito;
|
||||||
|
import org.mockito.stubbing.Answer;
|
||||||
|
|
||||||
|
public class LazyLambdaThreadSafeSupplierUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCalledMultipleTimes_thenShouldBeCalledOnlyOnce() {
|
||||||
|
@SuppressWarnings("unchecked") Supplier<String> mockedExpensiveFunction = Mockito.mock(Supplier.class);
|
||||||
|
Mockito.when(mockedExpensiveFunction.get())
|
||||||
|
.thenReturn("expensive call");
|
||||||
|
LazyLambdaThreadSafeSupplier<String> testee = new LazyLambdaThreadSafeSupplier<>(mockedExpensiveFunction);
|
||||||
|
Mockito.verify(mockedExpensiveFunction, Mockito.never())
|
||||||
|
.get();
|
||||||
|
testee.getData();
|
||||||
|
testee.getData();
|
||||||
|
Mockito.verify(mockedExpensiveFunction, Mockito.times(1))
|
||||||
|
.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCalledMultipleTimesConcurrently_thenShouldBeCalledOnlyOnce() throws InterruptedException {
|
||||||
|
@SuppressWarnings("unchecked") Supplier<String> mockedExpensiveFunction = Mockito.mock(Supplier.class);
|
||||||
|
Mockito.when(mockedExpensiveFunction.get())
|
||||||
|
.thenAnswer((Answer<String>) invocation -> {
|
||||||
|
Thread.sleep(1000L);
|
||||||
|
return "Late response!";
|
||||||
|
});
|
||||||
|
LazyLambdaThreadSafeSupplier<String> testee = new LazyLambdaThreadSafeSupplier<>(mockedExpensiveFunction);
|
||||||
|
Mockito.verify(mockedExpensiveFunction, Mockito.never())
|
||||||
|
.get();
|
||||||
|
|
||||||
|
ExecutorService executorService = Executors.newFixedThreadPool(4);
|
||||||
|
executorService.invokeAll(List.of(testee::getData, testee::getData));
|
||||||
|
executorService.shutdown();
|
||||||
|
if (!executorService.awaitTermination(5, TimeUnit.SECONDS)) {
|
||||||
|
executorService.shutdownNow();
|
||||||
|
}
|
||||||
|
|
||||||
|
Mockito.verify(mockedExpensiveFunction, Mockito.times(1))
|
||||||
|
.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,59 @@
|
||||||
|
package com.baeldung.splitlargefile;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.FileOutputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.apache.commons.io.FilenameUtils;
|
||||||
|
|
||||||
|
class SplitLargeFile {
|
||||||
|
|
||||||
|
public List<File> splitByFileSize(File largeFile, int maxSizeOfSplitFiles,
|
||||||
|
String splitedFileDirPath) throws IOException {
|
||||||
|
List<File> listOfSplitFiles = new ArrayList<>();
|
||||||
|
try (InputStream in = Files.newInputStream(largeFile.toPath())) {
|
||||||
|
final byte[] buffer = new byte[maxSizeOfSplitFiles];
|
||||||
|
int dataRead = in.read(buffer);
|
||||||
|
while (dataRead > -1) {
|
||||||
|
File splitFile = getSplitFile(FilenameUtils.removeExtension(largeFile.getName()),
|
||||||
|
buffer, dataRead, splitedFileDirPath);
|
||||||
|
listOfSplitFiles.add(splitFile);
|
||||||
|
dataRead = in.read(buffer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return listOfSplitFiles;
|
||||||
|
}
|
||||||
|
|
||||||
|
private File getSplitFile(String largeFileName, byte[] buffer, int length,
|
||||||
|
String splitedFileDirPath) throws IOException {
|
||||||
|
File splitFile = File.createTempFile(largeFileName + "-", "-split",
|
||||||
|
new File(splitedFileDirPath));
|
||||||
|
try (FileOutputStream fos = new FileOutputStream(splitFile)) {
|
||||||
|
fos.write(buffer, 0, length);
|
||||||
|
}
|
||||||
|
return splitFile;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<File> splitByNumberOfFiles(File largeFile, int noOfFiles, String splitedFileDirPath)
|
||||||
|
throws IOException {
|
||||||
|
return splitByFileSize(largeFile, getSizeInBytes(largeFile.length(), noOfFiles),
|
||||||
|
splitedFileDirPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
private int getSizeInBytes(long largefileSizeInBytes, int numberOfFilesforSplit) {
|
||||||
|
if (largefileSizeInBytes % numberOfFilesforSplit != 0) {
|
||||||
|
largefileSizeInBytes = ((largefileSizeInBytes / numberOfFilesforSplit) + 1)
|
||||||
|
* numberOfFilesforSplit;
|
||||||
|
}
|
||||||
|
long x = largefileSizeInBytes / numberOfFilesforSplit;
|
||||||
|
if (x > Integer.MAX_VALUE) {
|
||||||
|
throw new NumberFormatException("size too large");
|
||||||
|
|
||||||
|
}
|
||||||
|
return (int) x;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,62 @@
|
||||||
|
package com.baeldung.outputstreamtobytearray;
|
||||||
|
|
||||||
|
import org.apache.commons.io.FileUtils;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.io.TempDir;
|
||||||
|
|
||||||
|
import java.io.*;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
public class OutputStreamToByteArrayUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenFileOutputStream_whenUsingFileUtilsToReadTheFile_thenReturnByteArray(@TempDir Path tempDir) throws IOException {
|
||||||
|
String data = "Welcome to Baeldung!";
|
||||||
|
String fileName = "file.txt";
|
||||||
|
Path filePath = tempDir.resolve(fileName);
|
||||||
|
|
||||||
|
try (FileOutputStream outputStream = new FileOutputStream(filePath.toFile())) {
|
||||||
|
outputStream.write(data.getBytes(StandardCharsets.UTF_8));
|
||||||
|
}
|
||||||
|
|
||||||
|
byte[] writtenData = FileUtils.readFileToByteArray(filePath.toFile());
|
||||||
|
String result = new String(writtenData, StandardCharsets.UTF_8);
|
||||||
|
assertEquals(data, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSystemOut_whenUsingDrainableOutputStream_thenReturnByteArray() throws IOException {
|
||||||
|
String data = "Welcome to Baeldung!\n";
|
||||||
|
|
||||||
|
DrainableOutputStream drainableOutputStream = new DrainableOutputStream(System.out);
|
||||||
|
try (drainableOutputStream) {
|
||||||
|
drainableOutputStream.write(data.getBytes(StandardCharsets.UTF_8));
|
||||||
|
}
|
||||||
|
|
||||||
|
byte[] writtenData = drainableOutputStream.toByteArray();
|
||||||
|
assertEquals(data, new String(writtenData, StandardCharsets.UTF_8));
|
||||||
|
}
|
||||||
|
|
||||||
|
public class DrainableOutputStream extends FilterOutputStream {
|
||||||
|
private final ByteArrayOutputStream buffer;
|
||||||
|
|
||||||
|
public DrainableOutputStream(OutputStream out) {
|
||||||
|
super(out);
|
||||||
|
this.buffer = new ByteArrayOutputStream();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void write(byte b[]) throws IOException {
|
||||||
|
buffer.write(b);
|
||||||
|
super.write(b);
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] toByteArray() {
|
||||||
|
return buffer.toByteArray();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,41 @@
|
||||||
|
package com.baeldung.splitlargefile;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
|
||||||
|
import org.junit.BeforeClass;
|
||||||
|
|
||||||
|
public class SplitLargeFileUnitTest {
|
||||||
|
|
||||||
|
@BeforeClass
|
||||||
|
public static void prepareData() throws IOException {
|
||||||
|
Files.createDirectories(Paths.get("target/split"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private String splitedFileDirPath() throws Exception {
|
||||||
|
return Paths.get("target").toString() + "/split";
|
||||||
|
}
|
||||||
|
|
||||||
|
private Path largeFilePath() throws Exception {
|
||||||
|
return Paths.get(this.getClass().getClassLoader().getResource("large-file.txt").toURI());
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@org.junit.Test
|
||||||
|
public void givenLargeFile_whenSplitLargeFile_thenSplitBySize() throws Exception {
|
||||||
|
File input = largeFilePath().toFile();
|
||||||
|
SplitLargeFile slf = new SplitLargeFile();
|
||||||
|
slf.splitByFileSize(input, 1024_000, splitedFileDirPath());
|
||||||
|
}
|
||||||
|
|
||||||
|
@org.junit.Test
|
||||||
|
public void givenLargeFile_whenSplitLargeFile_thenSplitByNumberOfFiles() throws Exception {
|
||||||
|
File input = largeFilePath().toFile();
|
||||||
|
SplitLargeFile slf = new SplitLargeFile();
|
||||||
|
slf.splitByNumberOfFiles(input, 3, splitedFileDirPath());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,2 @@
|
||||||
|
## Relevant Articles
|
||||||
|
- [Inter-Process Communication Methods in Java](https://www.baeldung.com/java-ipc)
|
|
@ -9,3 +9,5 @@ This module contains articles about core features in the Java language
|
||||||
- [Get a Random Element From a Set in Java](https://www.baeldung.com/java-set-draw-sample)
|
- [Get a Random Element From a Set in Java](https://www.baeldung.com/java-set-draw-sample)
|
||||||
- [Stop Executing Further Code in Java](https://www.baeldung.com/java-stop-running-code)
|
- [Stop Executing Further Code in Java](https://www.baeldung.com/java-stop-running-code)
|
||||||
- [Using the Apache Commons Lang 3 for Comparing Objects in Java](https://www.baeldung.com/java-apache-commons-lang-3-compare-objects)
|
- [Using the Apache Commons Lang 3 for Comparing Objects in Java](https://www.baeldung.com/java-apache-commons-lang-3-compare-objects)
|
||||||
|
- [Return First Non-null Value in Java](https://www.baeldung.com/java-first-non-null)
|
||||||
|
- [Static Final Variables in Java](https://www.baeldung.com/java-static-final-variables)
|
||||||
|
|
|
@ -23,6 +23,16 @@
|
||||||
<artifactId>commons-lang3</artifactId>
|
<artifactId>commons-lang3</artifactId>
|
||||||
<version>${commons-lang3.version}</version>
|
<version>${commons-lang3.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.openjdk.jmh</groupId>
|
||||||
|
<artifactId>jmh-core</artifactId>
|
||||||
|
<version>${jmh.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.openjdk.jmh</groupId>
|
||||||
|
<artifactId>jmh-generator-annprocess</artifactId>
|
||||||
|
<version>${jmh.version}</version>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
<build>
|
<build>
|
||||||
<plugins>
|
<plugins>
|
||||||
|
@ -39,6 +49,11 @@
|
||||||
<artifactId>mapstruct-processor</artifactId>
|
<artifactId>mapstruct-processor</artifactId>
|
||||||
<version>${mapstruct.version}</version>
|
<version>${mapstruct.version}</version>
|
||||||
</path>
|
</path>
|
||||||
|
<path>
|
||||||
|
<groupId>org.openjdk.jmh</groupId>
|
||||||
|
<artifactId>jmh-generator-annprocess</artifactId>
|
||||||
|
<version>${jmh.version}</version>
|
||||||
|
</path>
|
||||||
</annotationProcessorPaths>
|
</annotationProcessorPaths>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
@ -50,6 +65,7 @@
|
||||||
<maven.compiler.target>17</maven.compiler.target>
|
<maven.compiler.target>17</maven.compiler.target>
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
<mapstruct.version>1.6.0.Beta1</mapstruct.version>
|
<mapstruct.version>1.6.0.Beta1</mapstruct.version>
|
||||||
|
<jmh.version>1.37</jmh.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
|
@ -23,6 +23,23 @@ public class CompressByteArrayUtil {
|
||||||
return outputStream.toByteArray();
|
return outputStream.toByteArray();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static byte[] compressWithCustomLevel(byte[] input, int level) {
|
||||||
|
Deflater deflater = new Deflater();
|
||||||
|
deflater.setInput(input);
|
||||||
|
deflater.setLevel(level);
|
||||||
|
deflater.finish();
|
||||||
|
|
||||||
|
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||||
|
byte[] buffer = new byte[1024];
|
||||||
|
|
||||||
|
while (!deflater.finished()) {
|
||||||
|
int compressedSize = deflater.deflate(buffer);
|
||||||
|
outputStream.write(buffer, 0, compressedSize);
|
||||||
|
}
|
||||||
|
|
||||||
|
return outputStream.toByteArray();
|
||||||
|
}
|
||||||
|
|
||||||
public static byte[] decompress(byte[] input) throws DataFormatException {
|
public static byte[] decompress(byte[] input) throws DataFormatException {
|
||||||
Inflater inflater = new Inflater();
|
Inflater inflater = new Inflater();
|
||||||
inflater.setInput(input);
|
inflater.setInput(input);
|
||||||
|
|
|
@ -0,0 +1,14 @@
|
||||||
|
package com.baeldung.staticfinal;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
|
||||||
|
public class Bike {
|
||||||
|
public static final int TIRE = 2;
|
||||||
|
public static final int PEDAL;
|
||||||
|
public static final HashMap<String, Integer> PART = new HashMap<>();
|
||||||
|
|
||||||
|
static {
|
||||||
|
PEDAL = 5;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,39 @@
|
||||||
|
package com.baeldung.compressbytes;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.zip.DataFormatException;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
public class CompressByteArrayUnitTest {
|
||||||
|
|
||||||
|
private static final String INPUT_STRING = "Building a REST API is not a trivial task – from the high-level RESTful " +
|
||||||
|
"constraints down to the nitty-gritty of making everything work and work well." +
|
||||||
|
"Spring has made REST a first-class citizen and the platform has been maturing in leaps and bounds." +
|
||||||
|
"With this guide, my aim is to organize the mountains of information that are available on the subject and " +
|
||||||
|
"guide you through properly building an API." +
|
||||||
|
"The guide starts with the basics – bootstrapping the REST API, the Spring MVC Configuration, and basic customization.";
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenInputString_whenCompressWithDefaultLevel_thenDecompressWithSameSize() throws DataFormatException {
|
||||||
|
byte[] input = INPUT_STRING.getBytes();
|
||||||
|
byte[] compressedData = CompressByteArrayUtil.compress(input);
|
||||||
|
byte[] decompressedData = CompressByteArrayUtil.decompress(compressedData);
|
||||||
|
System.out.println("Original: " + input.length + " bytes");
|
||||||
|
System.out.println("Compressed: " + compressedData.length + " bytes");
|
||||||
|
System.out.println("Decompressed: " + decompressedData.length + " bytes");
|
||||||
|
assertEquals(input.length, decompressedData.length);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenInputString_whenCompressWithCustomLevel_thenDecompressWithSameSize() throws DataFormatException {
|
||||||
|
byte[] input = INPUT_STRING.getBytes();
|
||||||
|
byte[] compressedData = CompressByteArrayUtil.compressWithCustomLevel(input, 1);
|
||||||
|
byte[] decompressedData = CompressByteArrayUtil.decompress(compressedData);
|
||||||
|
System.out.println("Original: " + input.length + " bytes");
|
||||||
|
System.out.println("Compressed: " + compressedData.length + " bytes");
|
||||||
|
System.out.println("Decompressed: " + decompressedData.length + " bytes");
|
||||||
|
assertEquals(input.length, decompressedData.length);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,38 @@
|
||||||
|
package com.baeldung.recursivelysumintarray;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
public class RecursivelySumIntArrayUnitTest {
|
||||||
|
|
||||||
|
private static final int[] INT_ARRAY = { 1, 2, 3, 4, 5 };
|
||||||
|
|
||||||
|
static int sumIntArray1(int[] array) {
|
||||||
|
if (array.length == 1) {
|
||||||
|
return array[0];
|
||||||
|
} else {
|
||||||
|
return array[0] + sumIntArray1(Arrays.copyOfRange(array, 1, array.length));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static int sumIntArray2(int[] array, int index) {
|
||||||
|
if (index == 0) {
|
||||||
|
return array[index];
|
||||||
|
} else {
|
||||||
|
return array[index] + sumIntArray2(array, index - 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingSumIntArray1_thenGetExpectedResult() {
|
||||||
|
assertEquals(15, sumIntArray1(INT_ARRAY));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingSumIntArray2_thenGetExpectedResult() {
|
||||||
|
assertEquals(15, sumIntArray2(INT_ARRAY, INT_ARRAY.length - 1));
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,61 @@
|
||||||
|
package com.baeldung.recursivelysumintarray;
|
||||||
|
|
||||||
|
import static com.baeldung.recursivelysumintarray.RecursivelySumIntArrayUnitTest.sumIntArray1;
|
||||||
|
import static com.baeldung.recursivelysumintarray.RecursivelySumIntArrayUnitTest.sumIntArray2;
|
||||||
|
|
||||||
|
import java.util.Random;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
import org.openjdk.jmh.annotations.Benchmark;
|
||||||
|
import org.openjdk.jmh.annotations.BenchmarkMode;
|
||||||
|
import org.openjdk.jmh.annotations.Fork;
|
||||||
|
import org.openjdk.jmh.annotations.Measurement;
|
||||||
|
import org.openjdk.jmh.annotations.Mode;
|
||||||
|
import org.openjdk.jmh.annotations.OutputTimeUnit;
|
||||||
|
import org.openjdk.jmh.annotations.Param;
|
||||||
|
import org.openjdk.jmh.annotations.Scope;
|
||||||
|
import org.openjdk.jmh.annotations.Setup;
|
||||||
|
import org.openjdk.jmh.annotations.State;
|
||||||
|
import org.openjdk.jmh.annotations.Warmup;
|
||||||
|
import org.openjdk.jmh.runner.Runner;
|
||||||
|
import org.openjdk.jmh.runner.options.Options;
|
||||||
|
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||||
|
|
||||||
|
@BenchmarkMode(Mode.AverageTime)
|
||||||
|
@State(Scope.Thread)
|
||||||
|
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||||
|
@Warmup(iterations = 2)
|
||||||
|
@Fork(1)
|
||||||
|
@Measurement(iterations = 5)
|
||||||
|
public class SumArrayBenchmark {
|
||||||
|
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
Options options = new OptionsBuilder().include(SumArrayBenchmark.class.getSimpleName())
|
||||||
|
.build();
|
||||||
|
new Runner(options).run();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Param({ "10", "10000" })
|
||||||
|
public int size;
|
||||||
|
int[] array;
|
||||||
|
|
||||||
|
@Setup
|
||||||
|
public void setup() {
|
||||||
|
var r = new Random();
|
||||||
|
array = new int[size];
|
||||||
|
|
||||||
|
for (int i = 0; i < size; i++) {
|
||||||
|
array[i] = r.nextInt();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public int withArrayCopy() {
|
||||||
|
return sumIntArray1(array);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public int withoutArrayCopy() {
|
||||||
|
return sumIntArray2(array, array.length - 1);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,33 @@
|
||||||
|
package com.baeldung.staticfinal;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
class BikeUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenTireConstantSetUponDeclaration_whenGetTire_thenReturnTwo() {
|
||||||
|
assertEquals(2, Bike.TIRE);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenPedalConstantSetByStaticBlock_whenGetPedal_thenReturnFive() {
|
||||||
|
assertEquals(5, Bike.PEDAL);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenPartConstantObject_whenObjectStateChanged_thenCorrect() {
|
||||||
|
Bike.PART.put("seat", 1);
|
||||||
|
assertEquals(1, Bike.PART.get("seat"));
|
||||||
|
|
||||||
|
Bike.PART.put("seat", 5);
|
||||||
|
assertEquals(5, Bike.PART.get("seat"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenMathClass_whenAccessingPiConstant_thenVerifyPiValueIsCorrect() {
|
||||||
|
assertEquals(3.141592653589793, Math.PI);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -5,6 +5,14 @@
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<artifactId>core-java-lang-math</artifactId>
|
<artifactId>core-java-lang-math</artifactId>
|
||||||
<name>core-java-lang-math</name>
|
<name>core-java-lang-math</name>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.projectlombok</groupId>
|
||||||
|
<artifactId>lombok</artifactId>
|
||||||
|
<version>1.18.24</version>
|
||||||
|
<scope>compile</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
<packaging>jar</packaging>
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
|
|
|
@ -0,0 +1,20 @@
|
||||||
|
package com.baeldung.algorithms.percentage;
|
||||||
|
|
||||||
|
import lombok.experimental.ExtensionMethod;
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.util.Scanner;
|
||||||
|
|
||||||
|
@ExtensionMethod(FastBigDecimalPercentage.class)
|
||||||
|
public class BigDecimalPercentageCalculator {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
|
||||||
|
Scanner in = new Scanner(System.in);
|
||||||
|
System.out.println("Enter obtained marks:");
|
||||||
|
BigDecimal obtained = new BigDecimal(in.nextDouble());
|
||||||
|
System.out.println("Enter total marks:");
|
||||||
|
BigDecimal total = new BigDecimal(in.nextDouble());
|
||||||
|
|
||||||
|
System.out.println("Percentage obtained :"+ obtained.toPercentageOf(total));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,18 @@
|
||||||
|
package com.baeldung.algorithms.percentage;
|
||||||
|
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.math.RoundingMode;
|
||||||
|
|
||||||
|
public class BigDecimalPercentages {
|
||||||
|
|
||||||
|
private static final BigDecimal ONE_HUNDRED = new BigDecimal("100");
|
||||||
|
|
||||||
|
public BigDecimal toPercentageOf(BigDecimal value, BigDecimal total) {
|
||||||
|
return value.divide(total, 4, RoundingMode.HALF_UP).multiply(ONE_HUNDRED);
|
||||||
|
}
|
||||||
|
|
||||||
|
public BigDecimal percentOf(BigDecimal percentage, BigDecimal total) {
|
||||||
|
return percentage.multiply(total).divide(ONE_HUNDRED, 2, RoundingMode.HALF_UP);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,16 @@
|
||||||
|
package com.baeldung.algorithms.percentage;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.math.RoundingMode;
|
||||||
|
|
||||||
|
public class FastBigDecimalPercentage {
|
||||||
|
|
||||||
|
public static BigDecimal toPercentageOf(BigDecimal value, BigDecimal total) {
|
||||||
|
return value.divide(total, 4, RoundingMode.HALF_UP).scaleByPowerOfTen(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static BigDecimal percentOf(BigDecimal percentage, BigDecimal total) {
|
||||||
|
return percentage.multiply(total).scaleByPowerOfTen(-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,27 @@
|
||||||
|
package com.baeldung.algorithms.percentage;
|
||||||
|
|
||||||
|
import org.hamcrest.number.BigDecimalCloseTo;
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
|
||||||
|
public class BigDecimalPercentageUnitTest {
|
||||||
|
private BigDecimalPercentages pc = new BigDecimalPercentages();
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldConvertToPercentageOfTotal(){
|
||||||
|
BigDecimalCloseTo expected = new BigDecimalCloseTo(new BigDecimal(5.05), new BigDecimal(0.001));
|
||||||
|
Assert.assertTrue("Result not as expected",expected.matchesSafely(
|
||||||
|
pc.toPercentageOf(new BigDecimal(50.5),new BigDecimal(1000))));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldCalculatePercentageOfTotal(){
|
||||||
|
BigDecimalCloseTo expected = new BigDecimalCloseTo(new BigDecimal(31.40), new BigDecimal(0.001));
|
||||||
|
Assert.assertTrue("Result not as expected",expected.matchesSafely(
|
||||||
|
pc.percentOf(new BigDecimal(3.14),new BigDecimal(1000))));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,27 @@
|
||||||
|
package com.baeldung.algorithms.percentage;
|
||||||
|
|
||||||
|
import org.hamcrest.number.BigDecimalCloseTo;
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
|
||||||
|
public class FastBigDecimalPercentageUnitTest {
|
||||||
|
private FastBigDecimalPercentage pc = new FastBigDecimalPercentage();
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldConvertToPercentageOfTotal(){
|
||||||
|
BigDecimalCloseTo expected = new BigDecimalCloseTo(new BigDecimal(5.05), new BigDecimal(0.001));
|
||||||
|
Assert.assertTrue("Result not as expected",expected.matchesSafely(
|
||||||
|
pc.toPercentageOf(new BigDecimal(50.5),new BigDecimal(1000))));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldCalculatePercentageOfTotal(){
|
||||||
|
BigDecimalCloseTo expected = new BigDecimalCloseTo(new BigDecimal(31.40), new BigDecimal(0.001));
|
||||||
|
Assert.assertTrue("Result not as expected",expected.matchesSafely(
|
||||||
|
pc.percentOf(new BigDecimal(3.14),new BigDecimal(1000))));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -10,3 +10,4 @@ This module contains articles about Java operators
|
||||||
- [Check if at Least Two Out of Three Booleans Are True in Java](https://www.baeldung.com/java-check-two-of-three-booleans)
|
- [Check if at Least Two Out of Three Booleans Are True in Java](https://www.baeldung.com/java-check-two-of-three-booleans)
|
||||||
- [Alternatives for instanceof Operator in Java](https://www.baeldung.com/java-instanceof-alternatives)
|
- [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)
|
- [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)
|
||||||
|
|
|
@ -0,0 +1,178 @@
|
||||||
|
package com.baeldung.colonexamples;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Examples of the different ways Java uses the colon (:) character.
|
||||||
|
*/
|
||||||
|
public class ColonExamples {
|
||||||
|
|
||||||
|
private final static Logger LOG = LoggerFactory.getLogger(ColonExamples.class);
|
||||||
|
|
||||||
|
public void example1_enhancedForLoop() {
|
||||||
|
|
||||||
|
// Original style
|
||||||
|
for(int i = 0; i < 10; i++) {
|
||||||
|
// do something
|
||||||
|
}
|
||||||
|
|
||||||
|
// Using enhanced for loop
|
||||||
|
int[] numbers = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9};
|
||||||
|
for(int i : numbers) {
|
||||||
|
// do something
|
||||||
|
}
|
||||||
|
|
||||||
|
// Using List instead of array
|
||||||
|
List<Integer> numbersList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
|
||||||
|
for(Integer i : numbersList) {
|
||||||
|
// do something
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void example2_switchStatement(String animal) {
|
||||||
|
|
||||||
|
// Original style
|
||||||
|
if(animal.equals("cat")) {
|
||||||
|
System.out.println("meow");
|
||||||
|
}
|
||||||
|
else if(animal.equals("lion")) {
|
||||||
|
System.out.println("roar");
|
||||||
|
}
|
||||||
|
else if(animal.equals("dog") || animal.equals("seal")) {
|
||||||
|
System.out.println("bark");
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
System.out.println("unknown");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Using switch statement
|
||||||
|
switch(animal) {
|
||||||
|
case "cat":
|
||||||
|
System.out.println("meow");
|
||||||
|
break;
|
||||||
|
case "lion":
|
||||||
|
System.out.println("roar");
|
||||||
|
break;
|
||||||
|
case "dog":
|
||||||
|
case "seal":
|
||||||
|
System.out.println("bark");
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
System.out.println("unknown");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void example3_labels() {
|
||||||
|
|
||||||
|
// For loops without labels
|
||||||
|
for(int i = 0; i < 10; i++) {
|
||||||
|
for (int j = 0; j < 10; j++) {
|
||||||
|
if (checkSomeCondition()) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
outterLoop: for(int i = 0; i < 10; i++) {
|
||||||
|
innerLoop: for (int j = 0; j < 10; j++) {
|
||||||
|
if (checkSomeCondition()) {
|
||||||
|
break outterLoop;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void example4_ternaryOperator() {
|
||||||
|
|
||||||
|
// Original way using if/else
|
||||||
|
int x;
|
||||||
|
if(checkSomeCondition()) {
|
||||||
|
x = 1;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
x = 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Using ternary operator
|
||||||
|
x = checkSomeCondition() ? 1 : 2;
|
||||||
|
|
||||||
|
// Using with other statements
|
||||||
|
boolean remoteCallResult = callRemoteApi();
|
||||||
|
LOG.info(String.format(
|
||||||
|
"The result of the remote API call %s successful",
|
||||||
|
remoteCallResult ? "was" : "was not"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
public void example5_methodReferences() {
|
||||||
|
// Original way without lambdas and method references
|
||||||
|
List<String> names = Arrays.asList("ross", "joey", "chandler");
|
||||||
|
List<String> upperCaseNames = new ArrayList<>();
|
||||||
|
for(String name : names) {
|
||||||
|
upperCaseNames.add(name.toUpperCase());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Using method reference with stream map operation
|
||||||
|
List<String> petNames = Arrays.asList("ross", "joey", "chandler");
|
||||||
|
List<String> petUpperCaseNames = petNames
|
||||||
|
.stream()
|
||||||
|
.map(String::toUpperCase)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
|
// Method reference with stream filter
|
||||||
|
List<Animal> pets = Arrays.asList(new Cat(), new Dog(), new Parrot());
|
||||||
|
List<Animal> onlyDogs = pets
|
||||||
|
.stream()
|
||||||
|
.filter(Dog.class::isInstance)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
|
// Method reference with constructors
|
||||||
|
Set<Animal> onlyDogsSet = pets
|
||||||
|
.stream()
|
||||||
|
.filter(Dog.class::isInstance)
|
||||||
|
.collect(Collectors.toCollection(TreeSet::new));
|
||||||
|
}
|
||||||
|
|
||||||
|
public void example6_asserttion() {
|
||||||
|
// Original way without assertions
|
||||||
|
Connection conn = getConnection();
|
||||||
|
if(conn == null) {
|
||||||
|
throw new RuntimeException("Connection is null");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Using assert keyword
|
||||||
|
assert getConnection() != null : "Connection is null";
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean checkSomeCondition() {
|
||||||
|
return new Random().nextBoolean();
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean callRemoteApi() {
|
||||||
|
return new Random().nextBoolean();
|
||||||
|
}
|
||||||
|
|
||||||
|
private Connection getConnection() {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static interface Animal {
|
||||||
|
|
||||||
|
}
|
||||||
|
private static class Dog implements Animal {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private static class Cat implements Animal {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private static class Parrot implements Animal {
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
|
@ -11,55 +11,55 @@ import static org.junit.jupiter.api.Assertions.*;
|
||||||
public class InstanceOfUnitTest {
|
public class InstanceOfUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void giveWhenInstanceIsCorrect_thenReturnTrue() {
|
void givenWhenInstanceIsCorrect_thenReturnTrue() {
|
||||||
Ring ring = new Ring();
|
Ring ring = new Ring();
|
||||||
assertTrue(ring instanceof Round);
|
assertTrue(ring instanceof Round);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void giveWhenObjectIsInstanceOfType_thenReturnTrue() {
|
void givenWhenObjectIsInstanceOfType_thenReturnTrue() {
|
||||||
Circle circle = new Circle();
|
Circle circle = new Circle();
|
||||||
assertTrue(circle instanceof Circle);
|
assertTrue(circle instanceof Circle);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void giveWhenInstanceIsOfSubtype_thenReturnTrue() {
|
void givenWhenInstanceIsOfSubtype_thenReturnTrue() {
|
||||||
Circle circle = new Circle();
|
Circle circle = new Circle();
|
||||||
assertTrue(circle instanceof Round);
|
assertTrue(circle instanceof Round);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void giveWhenTypeIsInterface_thenReturnTrue() {
|
void givenWhenTypeIsInterface_thenReturnTrue() {
|
||||||
Circle circle = new Circle();
|
Circle circle = new Circle();
|
||||||
assertTrue(circle instanceof Shape);
|
assertTrue(circle instanceof Shape);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void giveWhenTypeIsOfObjectType_thenReturnTrue() {
|
void givenWhenTypeIsOfObjectType_thenReturnTrue() {
|
||||||
Thread thread = new Thread();
|
Thread thread = new Thread();
|
||||||
assertTrue(thread instanceof Object);
|
assertTrue(thread instanceof Object);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void giveWhenInstanceValueIsNull_thenReturnFalse() {
|
void givenWhenInstanceValueIsNull_thenReturnFalse() {
|
||||||
Circle circle = null;
|
Circle circle = null;
|
||||||
assertFalse(circle instanceof Round);
|
assertFalse(circle instanceof Round);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void giveWhenComparingClassInDiffHierarchy_thenCompilationError() {
|
void givenWhenComparingClassInDiffHierarchy_thenCompilationError() {
|
||||||
//assertFalse( circle instanceof Triangle);
|
//assertFalse( circle instanceof Triangle);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void giveWhenStream_whenCastWithoutInstanceOfChk_thenGetException() {
|
void givenWhenStream_whenCastWithoutInstanceOfChk_thenGetException() {
|
||||||
Stream<Round> roundStream = Stream.of(new Ring(), new Ring(), new Circle());
|
Stream<Round> roundStream = Stream.of(new Ring(), new Ring(), new Circle());
|
||||||
assertThrows(ClassCastException.class, () -> roundStream.map(it -> (Ring) it).collect(Collectors.toList()));
|
assertThrows(ClassCastException.class, () -> roundStream.map(it -> (Ring) it).collect(Collectors.toList()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void giveWhenStream_whenCastAfterInstanceOfChk_thenGetExpectedResult() {
|
void givenWhenStream_whenCastAfterInstanceOfChk_thenGetExpectedResult() {
|
||||||
Stream<Round> roundStream = Stream.of(new Ring(), new Ring(), new Circle());
|
Stream<Round> roundStream = Stream.of(new Ring(), new Ring(), new Circle());
|
||||||
List<Ring> ringList = roundStream.filter(it -> it instanceof Ring).map(it -> (Ring) it).collect(Collectors.toList());
|
List<Ring> ringList = roundStream.filter(it -> it instanceof Ring).map(it -> (Ring) it).collect(Collectors.toList());
|
||||||
assertEquals(2, ringList.size());
|
assertEquals(2, ringList.size());
|
||||||
|
|
|
@ -0,0 +1 @@
|
||||||
|
## Relevant Articles
|
|
@ -0,0 +1,16 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<artifactId>core-java-loops</artifactId>
|
||||||
|
<name>core-java-loops</name>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung.core-java-modules</groupId>
|
||||||
|
<artifactId>core-java-modules</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
</project>
|
|
@ -0,0 +1,93 @@
|
||||||
|
package com.baeldung.loops;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Iterator;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.stream.IntStream;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
public class TheLastIterationInForEachUnitTest {
|
||||||
|
|
||||||
|
//@formatter:off
|
||||||
|
private static final List<String> MOVIES = List.of(
|
||||||
|
"Titanic",
|
||||||
|
"The Deer Hunter",
|
||||||
|
"Lord of the Rings",
|
||||||
|
"One Flew Over the Cuckoo's Nest",
|
||||||
|
"No Country For Old Men");
|
||||||
|
//@formatter:on
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingForEach_thenGetTheLastElementAfterTheLoop() {
|
||||||
|
String myLastMovie = "";
|
||||||
|
for (String movie : MOVIES) {
|
||||||
|
// ... work with movie
|
||||||
|
myLastMovie = movie;
|
||||||
|
}
|
||||||
|
assertEquals("No Country For Old Men", myLastMovie);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenLoopingWithIndexes_thenGetExpectedResult() {
|
||||||
|
int size = MOVIES.size();
|
||||||
|
String myLastMovie = null;
|
||||||
|
for (int i = 0; i < size; i++) {
|
||||||
|
String movie = MOVIES.get(i);
|
||||||
|
// ... work with movie
|
||||||
|
if (i == size - 1) {
|
||||||
|
myLastMovie = movie;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertEquals("No Country For Old Men", myLastMovie);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingIntStream_thenGetExpectedResult() {
|
||||||
|
int size = MOVIES.size();
|
||||||
|
final Map<Integer, String> myLastMovie = new HashMap<>();
|
||||||
|
IntStream.range(0, size)
|
||||||
|
.forEach(idx -> {
|
||||||
|
String movie = MOVIES.get(idx);
|
||||||
|
// ... work with movie
|
||||||
|
if (idx == size - 1) {
|
||||||
|
myLastMovie.put(idx, movie);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
assertEquals(1, myLastMovie.size());
|
||||||
|
assertTrue(myLastMovie.containsKey(size - 1));
|
||||||
|
assertTrue(myLastMovie.containsValue("No Country For Old Men"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingCounter_thenGetExpectedResult() {
|
||||||
|
int size = MOVIES.size();
|
||||||
|
String myLastMovie = null;
|
||||||
|
int cnt = 0;
|
||||||
|
for (String movie : MOVIES) {
|
||||||
|
// ... work with movie
|
||||||
|
if (++cnt == size) {
|
||||||
|
myLastMovie = movie;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertEquals("No Country For Old Men", myLastMovie);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingIterator_thenGetExpectedResult() {
|
||||||
|
String movie;
|
||||||
|
String myLastMovie = null;
|
||||||
|
for (Iterator<String> it = MOVIES.iterator(); it.hasNext(); ) {
|
||||||
|
movie = it.next();
|
||||||
|
// ... work with movie
|
||||||
|
if (!it.hasNext()) { // the last element
|
||||||
|
myLastMovie = movie;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertEquals("No Country For Old Men", myLastMovie);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,2 @@
|
||||||
|
## Relevant Articles
|
||||||
|
- [Check if a double Is an Integer in Java](https://www.baeldung.com/java-check-double-integer)
|
|
@ -0,0 +1,37 @@
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<artifactId>core-java-numbers-7</artifactId>
|
||||||
|
<name>core-java-numbers-7</name>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung.core-java-modules</groupId>
|
||||||
|
<artifactId>core-java-modules</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.jupiter</groupId>
|
||||||
|
<artifactId>junit-jupiter-engine</artifactId>
|
||||||
|
<version>${junit-jupiter.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.google.guava</groupId>
|
||||||
|
<artifactId>guava</artifactId>
|
||||||
|
<version>${guava.version}</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
<build>
|
||||||
|
<finalName>core-java-numbers-7</finalName>
|
||||||
|
<resources>
|
||||||
|
<resource>
|
||||||
|
<directory>src/main/resources</directory>
|
||||||
|
<filtering>true</filtering>
|
||||||
|
</resource>
|
||||||
|
</resources>
|
||||||
|
</build>
|
||||||
|
</project>
|
|
@ -0,0 +1,39 @@
|
||||||
|
package com.baeldung.bigdecimalzero;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
public class BigDecimalZeroVsNewBigDecimalUnitTest {
|
||||||
|
@Test
|
||||||
|
void whenComparingZeroAndNewBigDecimal_thenGetExpectedResult() {
|
||||||
|
BigDecimal bd1 = new BigDecimal("42.00");
|
||||||
|
BigDecimal bd2 = new BigDecimal("42.0000");
|
||||||
|
assertEquals(0, bd1.compareTo(bd2));
|
||||||
|
|
||||||
|
assertNotEquals(bd1, bd2);
|
||||||
|
|
||||||
|
BigDecimal zero0 = new BigDecimal(0);
|
||||||
|
assertNotEquals(zero0, new BigDecimal("0.000"));
|
||||||
|
|
||||||
|
BigDecimal zero = BigDecimal.ZERO;
|
||||||
|
assertEquals(zero, zero0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenCallingBigDecimalZero_thenAlwaysGetTheSameObject() {
|
||||||
|
BigDecimal z1 = BigDecimal.ZERO;
|
||||||
|
BigDecimal z2 = BigDecimal.ZERO;
|
||||||
|
assertSame(z1, z2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenCallingNewBigDecimal_thenAlwaysGetTheSameObject() {
|
||||||
|
BigDecimal z1 = new BigDecimal(0);
|
||||||
|
BigDecimal z2 = new BigDecimal(0);
|
||||||
|
assertNotSame(z1, z2);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,83 @@
|
||||||
|
package com.baeldung.doubleisint;
|
||||||
|
|
||||||
|
import com.google.common.math.DoubleMath;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
public class CheckDoubleIsAnIntegerUnitTest {
|
||||||
|
|
||||||
|
boolean notNaNOrInfinity(double d) {
|
||||||
|
return !(Double.isNaN(d) || Double.isInfinite(d));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenConvertingToInt_thenGetExpectedResult() {
|
||||||
|
double d1 = 42.0D;
|
||||||
|
boolean d1IsInteger = notNaNOrInfinity(d1) && (int) d1 == d1;
|
||||||
|
assertTrue(d1IsInteger);
|
||||||
|
|
||||||
|
double d2 = 42.42D;
|
||||||
|
boolean d2IsInteger = notNaNOrInfinity(d2) && (int) d2 == d2;
|
||||||
|
assertFalse(d2IsInteger);
|
||||||
|
|
||||||
|
double d3 = 2.0D * Integer.MAX_VALUE;
|
||||||
|
boolean d3IsInteger = notNaNOrInfinity(d3) && (int) d3 == d3;
|
||||||
|
assertTrue(!d3IsInteger); // <-- fails if exceeding Integer's range
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingModuloOperator_thenGetExpectedResult() {
|
||||||
|
double d1 = 42.0D;
|
||||||
|
boolean d1IsInteger = notNaNOrInfinity(d1) && (d1 % 1) == 0;
|
||||||
|
assertTrue(d1IsInteger);
|
||||||
|
|
||||||
|
double d2 = 42.42D;
|
||||||
|
boolean d2IsInteger = notNaNOrInfinity(d2) && (d2 % 1) == 0;
|
||||||
|
assertFalse(d2IsInteger);
|
||||||
|
|
||||||
|
double d3 = 2.0D * Integer.MAX_VALUE;
|
||||||
|
boolean d3IsInteger = notNaNOrInfinity(d3) && (d3 % 1) == 0;
|
||||||
|
assertTrue(d3IsInteger);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenCheckingFloorOrCeilingValue_thenGetExpectedResult() {
|
||||||
|
double d1 = 42.0D;
|
||||||
|
boolean d1IsInteger = notNaNOrInfinity(d1) && Math.floor(d1) == d1;
|
||||||
|
assertTrue(d1IsInteger);
|
||||||
|
|
||||||
|
double d2 = 42.42D;
|
||||||
|
boolean d2IsInteger = notNaNOrInfinity(d2) && Math.floor(d2) == d2;
|
||||||
|
assertFalse(d2IsInteger);
|
||||||
|
|
||||||
|
double d3 = 2.0D * Integer.MAX_VALUE;
|
||||||
|
boolean d3IsInteger = notNaNOrInfinity(d3) && Math.floor(d3) == d3;
|
||||||
|
assertTrue(d3IsInteger);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingGuava_thenGetExpectedResult() {
|
||||||
|
double d1 = 42.0D;
|
||||||
|
boolean d1IsInteger = DoubleMath.isMathematicalInteger(d1);
|
||||||
|
assertTrue(d1IsInteger);
|
||||||
|
|
||||||
|
double d2 = 42.42D;
|
||||||
|
boolean d2IsInteger = DoubleMath.isMathematicalInteger(d2);
|
||||||
|
assertFalse(d2IsInteger);
|
||||||
|
|
||||||
|
double d3 = 2.0D * Integer.MAX_VALUE;
|
||||||
|
boolean d3IsInteger = DoubleMath.isMathematicalInteger(d3);
|
||||||
|
assertTrue(d3IsInteger);
|
||||||
|
|
||||||
|
boolean isInfinityInt = DoubleMath.isMathematicalInteger(Double.POSITIVE_INFINITY);
|
||||||
|
assertFalse(isInfinityInt);
|
||||||
|
|
||||||
|
boolean isNanInt = DoubleMath.isMathematicalInteger(Double.NaN);
|
||||||
|
assertFalse(isNanInt);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,113 @@
|
||||||
|
package com.baeldung.withoutscientificnotation;
|
||||||
|
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.io.PrintStream;
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.text.DecimalFormat;
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.AfterEach;
|
||||||
|
import org.junit.jupiter.api.Assertions;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
class PrintDoubleWithoutScientificNotationUnitTest {
|
||||||
|
|
||||||
|
private final PrintStream standardOut = System.out;
|
||||||
|
private final ByteArrayOutputStream outputStreamCaptor = new ByteArrayOutputStream();
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
public void setUp() {
|
||||||
|
System.setOut(new PrintStream(outputStreamCaptor));
|
||||||
|
Locale.setDefault(Locale.US);
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterEach
|
||||||
|
public void tearDown() {
|
||||||
|
System.setOut(standardOut);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenLargeNumber_whenPrintWithDecimalFormat_thenOutputIsWithoutScientificNotation() {
|
||||||
|
|
||||||
|
DecimalFormat df = new DecimalFormat("#.###########");
|
||||||
|
double largeNumber = 256450000d;
|
||||||
|
System.out.println("Large Number: " + df.format(largeNumber));
|
||||||
|
|
||||||
|
Assertions.assertEquals("Large Number: 256450000", outputStreamCaptor.toString()
|
||||||
|
.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenSmallNumber_whenPrintWithDecimalFormat_thenOutputIsWithoutScientificNotation() {
|
||||||
|
|
||||||
|
DecimalFormat df = new DecimalFormat("#.###########");
|
||||||
|
double smallNumber = 0.0000046d;
|
||||||
|
System.out.println("Small Number: " + df.format(smallNumber));
|
||||||
|
|
||||||
|
Assertions.assertEquals("Small Number: 0.0000046", outputStreamCaptor.toString()
|
||||||
|
.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenLargeNumber_whenPrintWithPrintf_thenOutputIsWithoutScientificNotation() {
|
||||||
|
|
||||||
|
double largeNumber = 256450000d;
|
||||||
|
System.out.printf("Large Number: %.7f", largeNumber);
|
||||||
|
|
||||||
|
Assertions.assertEquals("Large Number: 256450000.0000000", outputStreamCaptor.toString()
|
||||||
|
.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenSmallNumber_whenPrintWithPrintf_thenOutputIsWithoutScientificNotation() {
|
||||||
|
|
||||||
|
double smallNumber = 0.0000046d;
|
||||||
|
System.out.printf("Small Number: %.7f", smallNumber);
|
||||||
|
|
||||||
|
Assertions.assertEquals("Small Number: 0.0000046", outputStreamCaptor.toString()
|
||||||
|
.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenLargeNumber_whenPrintWithBigDecimal_thenOutputIsWithoutScientificNotation() {
|
||||||
|
|
||||||
|
double largeNumber = 256450000d;
|
||||||
|
System.out.println("Large Number: " + BigDecimal.valueOf(largeNumber).toPlainString());
|
||||||
|
|
||||||
|
Assertions.assertEquals("Large Number: 256450000", outputStreamCaptor.toString()
|
||||||
|
.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenSmallNumber_whenPrintWithBigDecimal_thenOutputIsWithoutScientificNotation() {
|
||||||
|
|
||||||
|
double smallNumber = 0.0000046d;
|
||||||
|
System.out.println("Small Number: " + BigDecimal.valueOf(smallNumber).toPlainString());
|
||||||
|
|
||||||
|
Assertions.assertEquals("Small Number: 0.0000046", outputStreamCaptor.toString()
|
||||||
|
.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenLargeNumber_whenPrintWithStringFormat_thenOutputIsWithoutScientificNotation() {
|
||||||
|
|
||||||
|
double largeNumber = 256450000d;
|
||||||
|
String formattedLargeNumber = String.format("%.7f", largeNumber);
|
||||||
|
System.out.println("Large Number: " + formattedLargeNumber);
|
||||||
|
|
||||||
|
Assertions.assertEquals("Large Number: 256450000.0000000", outputStreamCaptor.toString()
|
||||||
|
.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenSmallNumber_whenPrintWithStringFormat_thenOutputIsWithoutScientificNotation() {
|
||||||
|
|
||||||
|
double smallNumber = 0.0000046d;
|
||||||
|
String formattedSmallNumber = String.format("%.7f", smallNumber);
|
||||||
|
System.out.println("Small Number: " + formattedSmallNumber);
|
||||||
|
|
||||||
|
Assertions.assertEquals("Small Number: 0.0000046", outputStreamCaptor.toString()
|
||||||
|
.trim());
|
||||||
|
}
|
||||||
|
}
|
|
@ -4,3 +4,5 @@
|
||||||
- [Convert int to Long in Java](https://www.baeldung.com/java-convert-int-long)
|
- [Convert int to Long in Java](https://www.baeldung.com/java-convert-int-long)
|
||||||
- [How To Convert Double To Float In Java](https://www.baeldung.com/java-convert-double-float)
|
- [How To Convert Double To Float In Java](https://www.baeldung.com/java-convert-double-float)
|
||||||
- [Converting from float to BigDecimal in Java](https://www.baeldung.com/java-convert-float-bigdecimal)
|
- [Converting from float to BigDecimal in Java](https://www.baeldung.com/java-convert-float-bigdecimal)
|
||||||
|
- [Convert Positive Integer to Negative and Vice Versa in Java](https://www.baeldung.com/java-negating-integer)
|
||||||
|
- [Rounding Up a Number to Nearest Multiple of 5 in Java](https://www.baeldung.com/java-round-nearest-multiple-five)
|
||||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue