Merge branch 'master' of github.com:eugenp/tutorials into BAEL-7271-junit-parameterresolver

This commit is contained in:
Lucian Snare 2024-01-01 22:45:02 -05:00
commit c172e8e13b
1127 changed files with 13116 additions and 3035 deletions

View File

@ -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)

View File

@ -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>

View File

@ -1,4 +1,4 @@
package com.baeldung.akka;
package com.baeldung.akkaactors;
import akka.actor.AbstractActor;
import akka.actor.Props;

View File

@ -1,4 +1,4 @@
package com.baeldung.akka;
package com.baeldung.akkaactors;
import akka.actor.AbstractActor;
import akka.event.Logging;

View File

@ -1,4 +1,4 @@
package com.baeldung.akka;
package com.baeldung.akkaactors;
import akka.actor.AbstractActor;
import akka.actor.Props;

View File

@ -1,4 +1,4 @@
package com.baeldung.akka;
package com.baeldung.akkaactors;
import akka.actor.AbstractActor;
import akka.actor.ActorRef;

View File

@ -1,4 +1,4 @@
package com.baeldung.akka;
package com.baeldung.akkaactors;
import akka.actor.AbstractActor;
import akka.event.Logging;

View File

@ -1,4 +1,4 @@
package com.baeldung.akka;
package com.baeldung.akkaactors;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;

View File

@ -14,6 +14,7 @@
</parent>
<modules>
<module>akka-actors</module>
<module>akka-http</module>
<module>akka-streams</module>
<module>spring-akka</module>

View File

@ -9,9 +9,8 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
@ -74,11 +73,6 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${maven.compiler.source.version}</source>
<target>${maven.compiler.target.version}</target>
</configuration>
</plugin>
</plugins>
</build>
@ -87,8 +81,6 @@
<assertj.version>3.22.0</assertj.version>
<mockserver.version>5.11.2</mockserver.version>
<httpclient5.version>5.2.1</httpclient5.version>
<maven.compiler.source.version>11</maven.compiler.source.version>
<maven.compiler.target.version>11</maven.compiler.target.version>
<spring-boot.version>2.1.7.RELEASE</spring-boot.version>
</properties>

View File

@ -9,9 +9,8 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>

View File

@ -61,9 +61,9 @@
<properties>
<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.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>
</properties>

View File

@ -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()));
}
}
}

View File

@ -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);
}
}

View File

@ -181,6 +181,7 @@
</build>
<properties>
<jackson.version>2.13.4</jackson.version>
<kafka.version>3.4.0</kafka.version>
<testcontainers-kafka.version>1.19.3</testcontainers-kafka.version>
<testcontainers-jupiter.version>1.15.3</testcontainers-jupiter.version>

View File

@ -29,7 +29,7 @@ import java.util.List;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
public class BackupCreatorIntegrationTest {
public class BackupCreatorUnitTest {
public static ObjectMapper mapper;
@Before

View File

@ -10,7 +10,7 @@ import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class WordCapitalizerIntegrationTest {
public class WordCapitalizerUnitTest {
@Test
public void givenDataSet_whenExecuteWordCapitalizer_thenReturnCapitalizedWords() throws Exception {

View File

@ -21,8 +21,7 @@ import org.junit.Ignore;
import org.junit.Test;
public class KafkaStreamsLiveTest {
private String bootstrapServers = "localhost:9092";
private Path stateDirectory;
private final String bootstrapServers = "localhost:9092";
@Test
@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.
try {
this.stateDirectory = Files.createTempDirectory("kafka-streams");
streamsConfiguration.put(StreamsConfig.STATE_DIR_CONFIG, this.stateDirectory.toAbsolutePath()
Path stateDirectory = Files.createTempDirectory("kafka-streams");
streamsConfiguration.put(StreamsConfig.STATE_DIR_CONFIG, stateDirectory.toAbsolutePath()
.toString());
} catch (final IOException e) {
throw new UncheckedIOException("Cannot create temporary directory", e);

View File

@ -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)

View File

@ -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>

View File

@ -40,22 +40,6 @@
<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>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>

View File

@ -34,22 +34,6 @@
<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>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>

View File

@ -63,6 +63,7 @@
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<version>${reactor.version}</version>
<scope>test</scope>
</dependency>
<dependency>
@ -93,6 +94,7 @@
<properties>
<spring.version>2.2.1.RELEASE</spring.version>
<awssdk.version>2.17.283</awssdk.version>
<reactor.version>3.6.0</reactor.version>
</properties>
</project>

View File

@ -39,27 +39,6 @@
</dependency>
</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>
<aws.java.sdk.version>2.20.52</aws.java.sdk.version>
<commons-codec-version>1.10.L001</commons-codec-version>

View File

@ -31,8 +31,8 @@
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<fork>true</fork>
<compilerArgument>-Xlint:all</compilerArgument>

View File

@ -26,7 +26,6 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${maven.compiler.source.version}</source>
<target>${maven.compiler.target.version}</target>

View File

@ -48,7 +48,6 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${maven.compiler.source.version}</source>
<target>${maven.compiler.target.version}</target>

View File

@ -27,7 +27,6 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<release>${maven.compiler.release}</release>
<compilerArgs>--enable-preview</compilerArgs>

View File

@ -27,7 +27,6 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<release>${maven.compiler.release}</release>
<compilerArgs>--enable-preview</compilerArgs>

View File

@ -19,7 +19,6 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<release>${maven.compiler.release}</release>
<compilerArgs>--enable-preview</compilerArgs>

View File

@ -1,3 +1,4 @@
## Relevant Articles
- [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)
- [Deserializing JSON to Java Record using Gson](https://www.baeldung.com/java-json-deserialize-record-gson)

View File

@ -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;
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -59,7 +59,6 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>

View File

@ -11,3 +11,4 @@ This module contains articles about arrays conversion in Java
- [Converting an int[] to HashSet in Java](https://www.baeldung.com/java-converting-int-array-to-hashset)
- [Convert an ArrayList of String to a String Array in Java](https://www.baeldung.com/java-convert-string-arraylist-array)
- [Convert Char Array to Int Array in Java](https://www.baeldung.com/java-convert-char-int-array)
- [How to Convert Byte Array to Char Array](https://www.baeldung.com/java-convert-byte-array-char)

View File

@ -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);
}
}

View File

@ -13,4 +13,20 @@
<version>0.0.1-SNAPSHOT</version>
</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>

View File

@ -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();
}
}

View File

@ -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);
}
}

View File

@ -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)
- [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)
- 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)

View File

@ -1,4 +1,4 @@
package com.baeldung.map.removeuplicate;
package com.baeldung.map.removeduplicate;
import static java.util.stream.Collectors.toMap;
import static org.assertj.core.api.Assertions.assertThat;

View File

@ -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)
- [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)
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-3)[[next -->]](/core-java-modules/core-java-collections-maps-5)

View File

@ -10,4 +10,5 @@
- [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)
- [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)

View File

@ -7,6 +7,7 @@
- [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)
- [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)
- [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)

View File

@ -7,3 +7,4 @@
- [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)
- [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)

View File

@ -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");
};
}
}

View File

@ -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";
};
}
}

View File

@ -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();
}
}

View File

@ -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();
}
}

View File

@ -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();
}
}

View File

@ -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();
}
}

View File

@ -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();
}
}

View File

@ -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();
}
}

View File

@ -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();
}
}

View File

@ -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();
}
}

View File

@ -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;
}
}

View File

@ -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();
}
}
}

View File

@ -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());
}
}

View File

@ -0,0 +1,2 @@
## Relevant Articles
- [Inter-Process Communication Methods in Java](https://www.baeldung.com/java-ipc)

View File

@ -10,3 +10,4 @@ This module contains articles about core features in the Java language
- [Stop Executing Further Code in Java](https://www.baeldung.com/java-stop-running-code)
- [Using the Apache Commons Lang 3 for Comparing Objects in Java](https://www.baeldung.com/java-apache-commons-lang-3-compare-objects)
- [Return First Non-null Value in Java](https://www.baeldung.com/java-first-non-null)
- [Static Final Variables in Java](https://www.baeldung.com/java-static-final-variables)

View File

@ -23,6 +23,16 @@
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
@ -39,6 +49,11 @@
<artifactId>mapstruct-processor</artifactId>
<version>${mapstruct.version}</version>
</path>
<path>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
@ -50,6 +65,7 @@
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<mapstruct.version>1.6.0.Beta1</mapstruct.version>
<jmh.version>1.37</jmh.version>
</properties>
</project>

View File

@ -23,6 +23,23 @@ public class CompressByteArrayUtil {
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 {
Inflater inflater = new Inflater();
inflater.setInput(input);

View File

@ -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;
}
}

View File

@ -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);
}
}

View File

@ -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));
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -5,6 +5,14 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-lang-math</artifactId>
<name>core-java-lang-math</name>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>compile</scope>
</dependency>
</dependencies>
<packaging>jar</packaging>
<parent>

View File

@ -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));
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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))));
}
}

View File

@ -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))));
}
}

View File

@ -37,8 +37,8 @@
</build>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
</properties>
</project>

View File

@ -0,0 +1,33 @@
package com.baeldung.generics.classtype;
import java.util.ArrayList;
import java.util.List;
public class CollectionWithAndWithoutGenerics {
public static void main(String[] args) {
withoutGenerics();
}
private static void withoutGenerics() {
List container = new ArrayList();
container.add(1);
container.add("2");
container.add("string");
for (int i = 0; i < container.size(); i++) {
int val = (int) container.get(i);
}
}
public static void withGenerics() {
List<Integer> container = new ArrayList();
container.add(1);
container.add(2);
container.add(3);
for (int i = 0; i < container.size(); i++) {
int val = container.get(i);
}
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.generics.classtype;
public class ContainerTypeFromReflection<T> {
private T content;
public ContainerTypeFromReflection(T content) {
this.content = content;
}
public Class<?> getClazz() {
return this.content.getClass();
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.generics.classtype;
public class ContainerTypeFromTypeParameter<T> {
private Class<T> clazz;
public ContainerTypeFromTypeParameter(Class<T> clazz) {
this.clazz = clazz;
}
public Class<T> getClazz() {
return this.clazz;
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.generics.classtype;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
public abstract class TypeToken<T> {
private Type type;
protected TypeToken(){
Type superclass = getClass().getGenericSuperclass();
this.type = ((ParameterizedType) superclass).getActualTypeArguments()[0];
}
public Type getType() {
return type;
}
}

View File

@ -0,0 +1,47 @@
package com.baeldung.classtype;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import org.junit.jupiter.api.Test;
import com.baeldung.generics.classtype.ContainerTypeFromReflection;
import com.baeldung.generics.classtype.ContainerTypeFromTypeParameter;
import com.baeldung.generics.classtype.TypeToken;
public class GenericClassTypeUnitTest {
@Test
public void givenContainerClassWithGenericType_whenTypeParameterUsed_thenReturnsClassType() {
var stringContainer = new ContainerTypeFromTypeParameter<>(String.class);
Class<String> containerClass = stringContainer.getClazz();
assertEquals(containerClass, String.class);
}
@Test
public void givenContainerClassWithGenericType_whenReflectionUsed_thenReturnsClassType() {
var stringContainer = new ContainerTypeFromReflection<>("Hello Java");
Class<?> stringClazz = stringContainer.getClazz();
assertEquals(stringClazz, String.class);
var integerContainer = new ContainerTypeFromReflection<>(1);
Class<?> integerClazz = integerContainer.getClazz();
assertEquals(integerClazz, Integer.class);
}
@Test
public void giveContainerClassWithGenericType_whenTypeTokenUsed_thenReturnsClassType() {
class ContainerTypeFromTypeToken extends TypeToken<List<String>> {
}
var container = new ContainerTypeFromTypeToken();
ParameterizedType type = (ParameterizedType) container.getType();
Type actualTypeArgument = type.getActualTypeArguments()[0];
assertEquals(actualTypeArgument, String.class);
}
}

View File

@ -10,3 +10,4 @@ This module contains articles about Java operators
- [Check if at Least Two Out of Three Booleans Are True in Java](https://www.baeldung.com/java-check-two-of-three-booleans)
- [Alternatives for instanceof Operator in Java](https://www.baeldung.com/java-instanceof-alternatives)
- [What Does “––>” Mean in Java?](https://www.baeldung.com/java-minus-minus-greaterthan)
- [All the Ways Java Uses the Colon Character](https://www.baeldung.com/java-colon)

View File

@ -0,0 +1 @@
## Relevant Articles

View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-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>

View File

@ -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);
}
}

View File

@ -0,0 +1,2 @@
## Relevant Articles
- [Check if a double Is an Integer in Java](https://www.baeldung.com/java-check-double-integer)

View File

@ -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());
}
}

View File

@ -4,3 +4,5 @@
- [Convert int to Long in Java](https://www.baeldung.com/java-convert-int-long)
- [How To Convert Double To Float In Java](https://www.baeldung.com/java-convert-double-float)
- [Converting from float to BigDecimal in Java](https://www.baeldung.com/java-convert-float-bigdecimal)
- [Convert Positive Integer to Negative and Vice Versa in Java](https://www.baeldung.com/java-negating-integer)
- [Rounding Up a Number to Nearest Multiple of 5 in Java](https://www.baeldung.com/java-round-nearest-multiple-five)

View File

@ -9,7 +9,7 @@ import org.slf4j.LoggerFactory;
public class CombiningUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(CombiningUnitTest.class);
public static final int TOP = 10000000;
public static final int TOP = 1000000;
public static final double FRACTION = 0.1;
@Test

View File

@ -12,7 +12,7 @@ import org.slf4j.LoggerFactory;
public class IfUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(IfUnitTest.class);
public static final int TOP = 10000000;
public static final int TOP = 1000000;
@Test
public void majorBranchSorted() {

View File

@ -11,7 +11,7 @@ import org.slf4j.LoggerFactory;
public class SortingUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(SortingUnitTest.class);
public static final int BIG = 10000000;
public static final int BIG = 1000000;
public static final int SMALL = 100000;
@Test

View File

@ -11,4 +11,4 @@ This module contains articles about the Stream API in Java.
- [Should We Close a Java Stream?](https://www.baeldung.com/java-stream-close)
- [Returning Stream vs. Collection](https://www.baeldung.com/java-return-stream-collection)
- [Convert a Java Enumeration Into a Stream](https://www.baeldung.com/java-enumeration-to-stream)
- More articles: [[<-- prev>]](/../core-java-streams-2)
- More articles: [[<-- prev>]](/../core-java-streams-2) [[next -->]](/../core-java-streams-4)

View File

@ -10,3 +10,4 @@
- [Understanding the Difference Between Stream.of() and IntStream.range()](https://www.baeldung.com/java-stream-of-and-intstream-range)
- [Check if Object Is an Array in Java](https://www.baeldung.com/java-check-if-object-is-an-array)
- [Mapping an Array of Integers to Strings Using Java Streams](https://www.baeldung.com/java-stream-integer-array-to-strings)
- More articles: [[<-- prev>]](/../core-java-streams-3) [[next -->]](/../core-java-streams-5)

View File

@ -71,7 +71,7 @@
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-core</artifactId>
<version>${io.reactor3.version}</version>
<version>${reactor-core.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
@ -121,7 +121,7 @@
<rx.java2.version>2.2.2</rx.java2.version>
<rx.java3.version>3.1.5</rx.java3.version>
<io.varv.version>1.0.0-alpha-4</io.varv.version>
<io.reactor3.version>3.5.1</io.reactor3.version>
<reactor-core.version>3.6.0</reactor-core.version>
<apache.commons.collection4.version>4.4</apache.commons.collection4.version>
<cyclops.version>10.4.1</cyclops.version>
</properties>

View File

@ -6,5 +6,7 @@
- [Partition a Stream in Java](https://www.baeldung.com/java-partition-stream)
- [Taking Every N-th Element from Finite and Infinite Streams in Java](https://www.baeldung.com/java-nth-element-finite-infinite-streams)
- [Modifying Objects Within Stream While Iterating](https://www.baeldung.com/java-stream-modify-objects-during-iteration)
- [Convert a Stream into a Map or Multimap in Java](https://www.baeldung.com/java-convert-stream-map-multimap)
- [How to Avoid NoSuchElementException in Stream API](https://www.baeldung.com/java-streams-api-avoid-nosuchelementexception)
- [Get Index of First Element Matching Boolean Using Java Streams](https://www.baeldung.com/java-streams-find-first-match-index)
- [Handling NullPointerException in findFirst() When the First Element Is Null](https://www.baeldung.com/java-handle-nullpointerexception-findfirst-first-null)
- More articles: [[<-- prev>]](/../core-java-streams-4)

View File

@ -67,7 +67,6 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>

View File

@ -0,0 +1,42 @@
package com.baeldung.findfirstnullpointerexception;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import org.junit.Test;
public class FindFirstNullPointerExceptionUnitTest {
private final List<String> inputs = Arrays.asList(null, "foo", "bar");
@Test(expected = NullPointerException.class)
public void givenStream_whenCallingFindFirst_thenThrowNullPointerException() {
Optional<String> firstElement = inputs.stream()
.findFirst();
}
@Test
public void givenStream_whenUsingOfNullableBeforeFindFirst_thenCorrect() {
Optional<String> firstElement = inputs.stream()
.map(Optional::ofNullable)
.findFirst()
.flatMap(Function.identity());
assertTrue(firstElement.isEmpty());
}
@Test
public void givenStream_whenUsingFilterBeforeFindFirst_thenCorrect() {
Optional<String> firstNonNullElement = inputs.stream()
.filter(Objects::nonNull)
.findFirst();
assertTrue(firstNonNullElement.isPresent());
}
}

View File

@ -34,7 +34,7 @@ public class FirstMatchingElementUnitTest {
@Test
public void whenUsingIntStream_thenFindFirstMatchingUserIndex() {
int index = IntStream.range(0, userList.size() - 1)
int index = IntStream.range(0, userList.size())
.filter(streamIndex -> searchName.equals(userList.get(streamIndex).getUserName()))
.findFirst()
.orElse(-1);

View File

@ -1,2 +1,3 @@
## Relevant Articles:
- [Handle Duplicate Keys When Producing Map Using Java Stream](https://www.baeldung.com/java-duplicate-keys-when-producing-map-using-stream)
- [Convert a Stream into a Map or Multimap in Java](https://www.baeldung.com/java-convert-stream-map-multimap)

View File

@ -46,7 +46,6 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>

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