Merge branch 'master' into master

This commit is contained in:
davidmartinezbarua
2024-01-26 21:18:19 -03:00
committed by GitHub
286 changed files with 5252 additions and 578 deletions
@@ -5,4 +5,5 @@
- [Getting Pixel Array From Image in Java](https://www.baeldung.com/java-getting-pixel-array-from-image)
- [Calculate Distance Between Two Coordinates in Java](https://www.baeldung.com/java-find-distance-between-points)
- [Rotate Arrays in Java](https://www.baeldung.com/java-rotate-arrays)
- [Find Missing Number From a Given Array in Java](https://www.baeldung.com/java-array-find-missing-number)
- More articles: [[<-- prev]](/algorithms-miscellaneous-6)
@@ -0,0 +1,153 @@
package com.baeldung.algorithms.weightedaverage;
import org.junit.jupiter.api.Test;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
import java.util.stream.IntStream;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class WeightedAverageUnitTest {
private List<Values> values = Arrays.asList(
new Values(1, 10),
new Values(3, 20),
new Values(5, 30),
new Values(7, 50),
new Values(9, 40)
);
private Double expected = 6.2;
@Test
void twoPass() {
double top = values.stream()
.mapToDouble(v -> v.value * v.weight)
.sum();
double bottom = values.stream()
.mapToDouble(v -> v.weight)
.sum();
double result = top / bottom;
assertEquals(expected, result);
}
@Test
void onePass() {
double top = 0;
double bottom = 0;
for (Values v : values) {
top += (v.value * v.weight);
bottom += v.weight;
}
double result = top / bottom;
assertEquals(expected, result);
}
@Test
void expanding() {
double result = values.stream()
.flatMap(v -> Collections.nCopies(v.weight, v.value).stream())
.mapToInt(v -> v)
.average()
.getAsDouble();
assertEquals(expected, result);
}
@Test
void reduce() {
class WeightedAverage {
final double top;
final double bottom;
public WeightedAverage(double top, double bottom) {
this.top = top;
this.bottom = bottom;
}
double average() {
return top / bottom;
}
}
double result = values.stream()
.reduce(new WeightedAverage(0, 0),
(acc, next) -> new WeightedAverage(
acc.top + (next.value * next.weight),
acc.bottom + next.weight),
(left, right) -> new WeightedAverage(
left.top + right.top,
left.bottom + right.bottom))
.average();
assertEquals(expected, result);
}
@Test
void customCollector() {
class WeightedAverage implements Collector<Values, WeightedAverage.RunningTotals, Double> {
class RunningTotals {
double top;
double bottom;
public RunningTotals() {
this.top = 0;
this.bottom = 0;
}
}
@Override
public Supplier<RunningTotals> supplier() {
return RunningTotals::new;
}
@Override
public BiConsumer<RunningTotals, Values> accumulator() {
return (current, next) -> {
current.top += (next.value * next.weight);
current.bottom += next.weight;
};
}
@Override
public BinaryOperator<RunningTotals> combiner() {
return (left, right) -> {
left.top += right.top;
left.bottom += right.bottom;
return left;
};
}
@Override
public Function<RunningTotals, Double> finisher() {
return rt -> rt.top / rt.bottom;
}
@Override
public Set<Characteristics> characteristics() {
return Collections.singleton(Characteristics.UNORDERED);
}
}
double result = values.stream()
.collect(new WeightedAverage());
assertEquals(expected, result);
}
private static class Values {
int value;
int weight;
public Values(int value, int weight) {
this.value = value;
this.weight = weight;
}
}
}
+1
View File
@@ -15,3 +15,4 @@ You can build the project from the command line using: *mvn clean install*, or i
- [bootstrap-server in Kafka Configuration](https://www.baeldung.com/java-kafka-bootstrap-server)
- [Introduction to Apache Kafka](https://www.baeldung.com/apache-kafka)
- [Ensuring Message Ordering in Kafka: Strategies and Configurations](https://www.baeldung.com/kafka-message-ordering)
- [Read Multiple Messages with Apache Kafka](https://www.baeldung.com/kafka-read-multiple-messages)
@@ -9,4 +9,5 @@
- [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)
- [Retrieving Unix Time in Java](https://www.baeldung.com/java-retrieve-unix-time)
- [Calculate Months Between Two Dates in Java](https://www.baeldung.com/java-months-difference-two-dates)
- [[<-- Prev]](/core-java-modules/core-java-datetime-java8-1)
@@ -0,0 +1,46 @@
package com.baeldung.daterangeoverlap;
import java.time.LocalDate;
import java.util.Calendar;
import org.joda.time.DateTime;
import org.joda.time.Interval;
public class DateRangeOverlapChecker {
public static boolean isOverlapUsingCalendarAndDuration(Calendar start1, Calendar end1, Calendar start2, Calendar end2) {
long overlap = Math.min(end1.getTimeInMillis(), end2.getTimeInMillis()) - Math.max(start1.getTimeInMillis(), start2.getTimeInMillis());
return overlap >= 0;
}
public static boolean isOverlapUsingLocalDateAndDuration(LocalDate start1, LocalDate end1, LocalDate start2, LocalDate end2) {
long overlap = Math.min(end1.toEpochDay(), end2.toEpochDay()) - Math.max(start1.toEpochDay(), start2.toEpochDay());
return overlap >= 0;
}
public static boolean isOverlapUsingJodaTime(DateTime start1, DateTime end1, DateTime start2, DateTime end2) {
Interval interval1 = new Interval(start1, end1);
Interval interval2 = new Interval(start2, end2);
return interval1.overlaps(interval2);
}
public static boolean isOverlapUsingCalendarAndCondition(Calendar start1, Calendar end1, Calendar start2, Calendar end2) {
return !(end1.before(start2) || start1.after(end2));
}
public static boolean isOverlapUsingLocalDateAndCondition(LocalDate start1, LocalDate end1, LocalDate start2, LocalDate end2) {
return !(end1.isBefore(start2) || start1.isAfter(end2));
}
public static boolean isOverlapUsingCalendarAndFindMin(Calendar start1, Calendar end1, Calendar start2, Calendar end2) {
long overlap1 = Math.min(end1.getTimeInMillis() - start1.getTimeInMillis(), end1.getTimeInMillis() - start2.getTimeInMillis());
long overlap2 = Math.min(end2.getTimeInMillis() - start2.getTimeInMillis(), end2.getTimeInMillis() - start1.getTimeInMillis());
return Math.min(overlap1, overlap2) / (24 * 60 * 60 * 1000) >= 0;
}
public static boolean isOverlapUsingLocalDateAndFindMin(LocalDate start1, LocalDate end1, LocalDate start2, LocalDate end2) {
long overlap1 = Math.min(end1.toEpochDay() - start1.toEpochDay(), end1.toEpochDay() - start2.toEpochDay());
long overlap2 = Math.min(end2.toEpochDay() - start2.toEpochDay(), end2.toEpochDay() - start1.toEpochDay());
return Math.min(overlap1, overlap2) >= 0;
}
}
@@ -0,0 +1,158 @@
package com.baeldung.daterangeoverlap;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.time.LocalDate;
import java.util.Calendar;
import org.joda.time.DateTime;
import org.junit.Test;
public class DateRangeOverlapCheckerUnitTest {
@Test
public void givenPartialOverlappingRanges_thenReturnsTrue() {
Calendar start1 = Calendar.getInstance();
start1.set(2024, 11, 15);
Calendar end1 = Calendar.getInstance();
end1.set(2024, 11, 20);
Calendar start2 = Calendar.getInstance();
start2.set(2024, 11, 18);
Calendar end2 = Calendar.getInstance();
end2.set(2024, 11, 22);
LocalDate startLD1 = LocalDate.of(2024, 12, 15);
LocalDate endLD1 = LocalDate.of(2024, 12, 20);
LocalDate startLD2 = LocalDate.of(2024, 12, 18);
LocalDate endLD2 = LocalDate.of(2024, 12, 22);
DateTime startJT1 = new DateTime(2024, 12, 15, 0, 0);
DateTime endJT1 = new DateTime(2024, 12, 20, 0, 0);
DateTime startJT2 = new DateTime(2024, 12, 18, 0, 0);
DateTime endJT2 = new DateTime(2024, 12, 22, 0, 0);
assertTrue(DateRangeOverlapChecker.isOverlapUsingCalendarAndDuration(start1, end1, start2, end2));
assertTrue(DateRangeOverlapChecker.isOverlapUsingLocalDateAndDuration(startLD1, endLD1, startLD2, endLD2));
assertTrue(DateRangeOverlapChecker.isOverlapUsingCalendarAndCondition(start1, end1, start2, end2));
assertTrue(DateRangeOverlapChecker.isOverlapUsingLocalDateAndCondition(startLD1, endLD1, startLD2, endLD2));
assertTrue(DateRangeOverlapChecker.isOverlapUsingCalendarAndFindMin(start1, end1, start2, end2));
assertTrue(DateRangeOverlapChecker.isOverlapUsingLocalDateAndFindMin(startLD1, endLD1, startLD2, endLD2));
assertTrue(DateRangeOverlapChecker.isOverlapUsingJodaTime(startJT1, endJT1, startJT2, endJT2));
}
@Test
public void givenFullOverlappingRanges_thenReturnsTrue() {
Calendar start1 = Calendar.getInstance();
start1.set(2024, 11, 15);
Calendar end1 = Calendar.getInstance();
end1.set(2024, 11, 20);
Calendar start2 = Calendar.getInstance();
start2.set(2024, 11, 16);
Calendar end2 = Calendar.getInstance();
end2.set(2024, 11, 18);
LocalDate startLD1 = LocalDate.of(2024, 12, 15);
LocalDate endLD1 = LocalDate.of(2024, 12, 20);
LocalDate startLD2 = LocalDate.of(2024, 12, 16);
LocalDate endLD2 = LocalDate.of(2024, 12, 18);
DateTime startJT1 = new DateTime(2024, 12, 15, 0, 0);
DateTime endJT1 = new DateTime(2024, 12, 20, 0, 0);
DateTime startJT2 = new DateTime(2024, 12, 16, 0, 0);
DateTime endJT2 = new DateTime(2024, 12, 18, 0, 0);
assertTrue(DateRangeOverlapChecker.isOverlapUsingCalendarAndDuration(start1, end1, start2, end2));
assertTrue(DateRangeOverlapChecker.isOverlapUsingLocalDateAndDuration(startLD1, endLD1, startLD2, endLD2));
assertTrue(DateRangeOverlapChecker.isOverlapUsingCalendarAndCondition(start1, end1, start2, end2));
assertTrue(DateRangeOverlapChecker.isOverlapUsingLocalDateAndCondition(startLD1, endLD1, startLD2, endLD2));
assertTrue(DateRangeOverlapChecker.isOverlapUsingCalendarAndFindMin(start1, end1, start2, end2));
assertTrue(DateRangeOverlapChecker.isOverlapUsingLocalDateAndFindMin(startLD1, endLD1, startLD2, endLD2));
assertTrue(DateRangeOverlapChecker.isOverlapUsingJodaTime(startJT1, endJT1, startJT2, endJT2));
}
@Test
public void givenConsecutiveRanges_thenReturnsFalse() {
Calendar start1 = Calendar.getInstance();
start1.set(2024, 11, 15);
Calendar end1 = Calendar.getInstance();
end1.set(2024, 11, 20);
Calendar start2 = Calendar.getInstance();
start2.set(2024, 11, 21);
Calendar end2 = Calendar.getInstance();
end2.set(2024, 11, 24);
LocalDate startLD1 = LocalDate.of(2024, 12, 15);
LocalDate endLD1 = LocalDate.of(2024, 12, 20);
LocalDate startLD2 = LocalDate.of(2024, 12, 21);
LocalDate endLD2 = LocalDate.of(2024, 12, 24);
DateTime startJT1 = new DateTime(2024, 12, 15, 0, 0);
DateTime endJT1 = new DateTime(2024, 12, 20, 0, 0);
DateTime startJT2 = new DateTime(2024, 12, 21, 0, 0);
DateTime endJT2 = new DateTime(2024, 12, 24, 0, 0);
assertFalse(DateRangeOverlapChecker.isOverlapUsingCalendarAndDuration(start1, end1, start2, end2));
assertFalse(DateRangeOverlapChecker.isOverlapUsingLocalDateAndDuration(startLD1, endLD1, startLD2, endLD2));
assertFalse(DateRangeOverlapChecker.isOverlapUsingCalendarAndCondition(start1, end1, start2, end2));
assertFalse(DateRangeOverlapChecker.isOverlapUsingLocalDateAndCondition(startLD1, endLD1, startLD2, endLD2));
assertFalse(DateRangeOverlapChecker.isOverlapUsingCalendarAndFindMin(start1, end1, start2, end2));
assertFalse(DateRangeOverlapChecker.isOverlapUsingLocalDateAndFindMin(startLD1, endLD1, startLD2, endLD2));
assertFalse(DateRangeOverlapChecker.isOverlapUsingJodaTime(startJT1, endJT1, startJT2, endJT2));
}
@Test
public void givenZeroRangeRanges_thenReturnsTrue() {
Calendar start1 = Calendar.getInstance();
start1.set(2024, 11, 15);
Calendar end1 = Calendar.getInstance();
end1.set(2024, 11, 20);
Calendar start2 = Calendar.getInstance();
start2.set(2024, 11, 20);
Calendar end2 = Calendar.getInstance();
end2.set(2024, 11, 20);
LocalDate startLD1 = LocalDate.of(2024, 12, 15);
LocalDate endLD1 = LocalDate.of(2024, 12, 20);
LocalDate startLD2 = LocalDate.of(2024, 12, 20);
LocalDate endLD2 = LocalDate.of(2024, 12, 20);
DateTime startJT1 = new DateTime(2024, 12, 15, 0, 0);
DateTime endJT1 = new DateTime(2024, 12, 20, 0, 0);
DateTime startJT2 = new DateTime(2024, 12, 20, 0, 0);
DateTime endJT2 = new DateTime(2024, 12, 20, 0, 0);
assertTrue(DateRangeOverlapChecker.isOverlapUsingCalendarAndDuration(start1, end1, start2, end2));
assertTrue(DateRangeOverlapChecker.isOverlapUsingLocalDateAndDuration(startLD1, endLD1, startLD2, endLD2));
assertTrue(DateRangeOverlapChecker.isOverlapUsingCalendarAndCondition(start1, end1, start2, end2));
assertTrue(DateRangeOverlapChecker.isOverlapUsingLocalDateAndCondition(startLD1, endLD1, startLD2, endLD2));
assertTrue(DateRangeOverlapChecker.isOverlapUsingCalendarAndFindMin(start1, end1, start2, end2));
assertTrue(DateRangeOverlapChecker.isOverlapUsingLocalDateAndFindMin(startLD1, endLD1, startLD2, endLD2));
//the overlaps method considers two intervals as overlapping only if they have a non-zero duration.
assertFalse(DateRangeOverlapChecker.isOverlapUsingJodaTime(startJT1, endJT1, startJT2, endJT2));
}
}
@@ -0,0 +1,36 @@
package com.baeldung.array.conversions;
import static org.assertj.core.api.Assertions.assertThat;
import org.apache.commons.lang3.ArrayUtils;
import org.junit.jupiter.api.Test;
public class ByteArrayToPrimitiveByteArrayUnitTest {
private static final byte[] EXPECTED_ARRAY_VALUES = {65, 66, 67, 68};
private static final Byte[] BYTE_ARRAY = {65, 66, 67, 68};
@Test
public void givenByteArray_whenConvertingUsingByteValue_thenGiveExpectedResult() {
byte[] newByteArray = new byte[BYTE_ARRAY.length];
for (int i = 0; i < BYTE_ARRAY.length; i++) {
newByteArray[i] = BYTE_ARRAY[i].byteValue();
}
assertThat(newByteArray).containsExactly(EXPECTED_ARRAY_VALUES);
}
@Test
public void givenByteArray_whenConvertingUsingUnboxing_thenGiveExpectedResult() {
byte[] newByteArray = new byte[BYTE_ARRAY.length];
for (int i = 0; i < BYTE_ARRAY.length; i++) {
newByteArray[i] = BYTE_ARRAY[i];
}
assertThat(newByteArray).containsExactly(EXPECTED_ARRAY_VALUES);
}
@Test
public void givenByteArray_whenConvertingArrayUtils_thenGiveExpectedResult() {
byte[] newByteArray = ArrayUtils.toPrimitive(BYTE_ARRAY);
assertThat(newByteArray).containsExactly(EXPECTED_ARRAY_VALUES);
}
}
@@ -0,0 +1,47 @@
package com.baeldung.array.conversions;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import org.apache.commons.lang3.ArrayUtils;
import org.junit.jupiter.api.Test;
public class PrimitiveByteArrayToByteArrayUnitTest {
private static final byte[] PRIMITIVE_BYTE_ARRAY = {65, 66, 67, 68};
private static final Byte[] EXPECTED_ARRAY_VALUES = {65, 66, 67, 68};
@Test
public void givenPrimitiveByteArray_whenConvertingUsingByteValueOf_thenGiveExpectedResult() {
Byte[] newByteArray = new Byte[PRIMITIVE_BYTE_ARRAY.length];
for (int i = 0; i < PRIMITIVE_BYTE_ARRAY.length; i++) {
newByteArray[i] = Byte.valueOf(PRIMITIVE_BYTE_ARRAY[i]);
}
assertThat(newByteArray).containsExactly(EXPECTED_ARRAY_VALUES);
}
@Test
public void givenPrimitiveByteArray_whenConvertingUsingAutoboxing_thenGiveExpectedResult() {
Byte[] newByteArray = new Byte[PRIMITIVE_BYTE_ARRAY.length];
for (int i = 0; i < PRIMITIVE_BYTE_ARRAY.length; i++) {
newByteArray[i] = PRIMITIVE_BYTE_ARRAY[i];
}
assertThat(newByteArray).containsExactly(EXPECTED_ARRAY_VALUES);
}
@Test
public void givenPrimitiveByteArray_whenConvertingUsingAutoboxingAndArraysSetAll_thenGiveExpectedResult() {
Byte[] newByteArray = new Byte[PRIMITIVE_BYTE_ARRAY.length];
Arrays.setAll(newByteArray, n -> PRIMITIVE_BYTE_ARRAY[n]);
assertThat(newByteArray)
.containsExactly(EXPECTED_ARRAY_VALUES);
}
@Test
public void givenPrimitiveByteArray_whenConvertingUsingArrayUtils_thenGiveExpectedResult() {
Byte[] newByteArray = ArrayUtils.toObject(PRIMITIVE_BYTE_ARRAY);
assertThat(newByteArray).containsExactly(EXPECTED_ARRAY_VALUES);
}
}
@@ -0,0 +1,70 @@
package com.baeldung.unicodechar;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class UnicodeCharFromCodePointHexStringUnitTest {
private static final String U_CHECK = "✅"; // U+2705
private static final String U_STRONG = "强"; // U+5F3A
@Test
void whenEscapeUAndNumberInString_thenGetExpectedUnicodeStr() {
String check = "\u2705";
assertEquals(U_CHECK, check);
String strong = "\u5F3A";
assertEquals(U_STRONG, strong);
// "A" U+0041
assertEquals("A", "\u0041");
}
@Test
void whenConcatUAndNumberAsString_thenDoNotGetExpectedUnicodeStr() {
String check = "\\u" + "2705";
assertEquals("\\u2705", check);
String strong = "\\u" + "5F3A";
assertEquals("\\u5F3A", strong);
}
@Test
void whenCastHexCodePointToCharAndConvertCharToString_thenGetExpectedUnicodeStr() {
int codePoint = Integer.parseInt("2705", 16); //Decimal int: 9989
char[] checkChar = Character.toChars(codePoint);
String check = String.valueOf(checkChar);
assertEquals(U_CHECK, check);
// For Java 11 and later versions
// assertEquals(U_CHECK, Character.toString(codePoint));
codePoint = Integer.parseInt("5F3A", 16); //Decimal int: 24378
char[] strongChar = Character.toChars(codePoint);
String strong = String.valueOf(strongChar);
assertEquals(U_STRONG, strong);
// For Java 11 and later versions
// assertEquals(U_STRONG, Character.toString(codePoint));
}
String stringFromCodePointHex(String codePointHex) {
int codePoint = Integer.parseInt(codePointHex, 16);
// For Java 11 and later versions: return Character.toString(codePoint)
char[] chars = Character.toChars(codePoint);
return String.valueOf(chars);
}
@Test
void whenUsingstringFromCodePointHex_thenGetExpectedUnicodeStr() {
assertEquals("A", stringFromCodePointHex("0041"));
assertEquals(U_CHECK, stringFromCodePointHex("2705"));
assertEquals(U_STRONG, stringFromCodePointHex("5F3A"));
}
}
@@ -11,4 +11,6 @@
- [Intro to Vector Class in Java](https://www.baeldung.com/java-vector-guide)
- [HashSet toArray() Method in Java](https://www.baeldung.com/java-hashset-toarray)
- [Time Complexity of Java Collections Sort in Java](https://www.baeldung.com/java-time-complexity-collections-sort)
- [Check if List Contains at Least One Enum](https://www.baeldung.com/java-list-check-enum-presence)
- [Comparison of for Loops and Iterators](https://www.baeldung.com/java-for-loops-vs-iterators)
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-4)
@@ -1,2 +1,5 @@
## Relevant Articles
- [Check if a List Contains a String Element While Ignoring Case](https://www.baeldung.com/java-list-search-case-insensitive)
- [Removing the Last Node in a Linked List](https://www.baeldung.com/java-linked-list-remove-last-element)
- [Call a Method on Each Element of a List in Java](https://www.baeldung.com/java-call-method-each-list-item)
- [Sorting One List Based on Another List in Java](https://www.baeldung.com/java-sorting-one-list-using-another)
@@ -12,4 +12,5 @@ This module contains articles about basic Java concurrency
- [How to Get the Number of Threads in a Java Process](https://www.baeldung.com/java-get-number-of-threads)
- [Set the Name of a Thread in Java](https://www.baeldung.com/java-set-thread-name)
- [Thread vs. Single Thread Executor Service](https://www.baeldung.com/java-single-thread-executor-service)
- [Difference Between a Future and a Promise in Java](https://www.baeldung.com/java-future-vs-promise-comparison)
- [[<-- Prev]](../core-java-concurrency-basic)[[Next -->]](../core-java-concurrency-basic-3)
@@ -13,4 +13,5 @@ This module contains articles about basic Java concurrency.
- [Retry Logic with CompletableFuture](https://www.baeldung.com/java-completablefuture-retry-logic)
- [Convert From List of CompletableFuture to CompletableFuture List](https://www.baeldung.com/java-completablefuture-list-convert)
- [Synchronize a Static Variable Among Different Threads](https://www.baeldung.com/java-synchronize-static-variable-different-threads)
- [Difference Between execute() and submit() in Executor Service](https://www.baeldung.com/java-execute-vs-submit-executor-service)
- [[<-- Prev]](../core-java-concurrency-basic-2)
@@ -0,0 +1,5 @@
## Core Date Operations (Part 4)
This module contains articles about date operations in Java.
### Relevant Articles:
@@ -0,0 +1,46 @@
<?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-date-operations-4</artifactId>
<name>core-java-date-operations-4</name>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>11</source>
<target>11</target>
</configuration>
</plugin>
</plugins>
</build>
<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>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${joda-time.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
</dependencies>
<properties>
<joda-time.version>2.12.6</joda-time.version>
</properties>
</project>
@@ -0,0 +1,46 @@
package com.baeldung.calculateweekdays;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.Arrays;
public class CalculateWeekdays {
public long getWorkingDaysWithStream(LocalDate start, LocalDate end){
return start.datesUntil(end)
.map(LocalDate::getDayOfWeek)
.filter(day -> !Arrays.asList(DayOfWeek.SATURDAY, DayOfWeek.SUNDAY).contains(day))
.count();
}
public long getWorkingDaysWithoutStream(LocalDate start, LocalDate end) {
boolean startOnWeekend = false;
// If starting at the weekend, move to following Monday
if(start.getDayOfWeek().getValue() > 5){
start = start.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
startOnWeekend = true;
}
boolean endOnWeekend = false;
// If ending at the weekend, move to previous Friday
if(end.getDayOfWeek().getValue() > 5){
end = end.with(TemporalAdjusters.previous(DayOfWeek.FRIDAY));
endOnWeekend = true;
}
// Cover case where starting on Saturday and ending following Sunday
if(start.isAfter(end)){
return 0;
}
// Get total weeks
long weeks = ChronoUnit.WEEKS.between(start, end);
long addValue = startOnWeekend || endOnWeekend ? 1 : 0;
// Add on days that did not make up a full week
return ( weeks * 5 ) + ( end.getDayOfWeek().getValue() - start.getDayOfWeek().getValue() ) + addValue;
}
}
@@ -0,0 +1,83 @@
package com.baeldung.calculateweekdays;
import static junit.framework.TestCase.assertEquals;
import java.time.LocalDate;
import org.junit.jupiter.api.Test;
public class CalculateWeekdaysUnitTest {
// Start Saturday end following Sunday (answer is 0)
LocalDate startTomorrow = LocalDate.of(2023, 12, 2);
LocalDate endTomorrow = LocalDate.of(2023, 12, 3);
// Three week gap with midweek start and finish (answer is 17)
LocalDate startThreeWeeks = LocalDate.of(2023, 11, 28);
LocalDate endThreeWeeks = LocalDate.of(2023, 12, 21);
// Three week gap with midweek start and weekend finish (answer is 17)
LocalDate startThreeWeeks2 = LocalDate.of(2023, 11, 6);
LocalDate endThreeWeeks2 = LocalDate.of(2023, 12, 30);
// Week gap start and end on weekend (answer is 40)
LocalDate startThreeWeeksWeekend = LocalDate.of(2023, 12, 2);
LocalDate endThreeWeeksWeekend = LocalDate.of(2023, 12, 9);
@Test
void givenTwoDaysOnSameWeekend_whenUsingStreams_thenCalculateWeekdays(){
CalculateWeekdays c = new CalculateWeekdays();
long result = c.getWorkingDaysWithStream(startTomorrow, endTomorrow);
assertEquals(0, result);
}
@Test
void givenTwoDaysOnSameWeekend_whenUsingMaths_thenCalculateWeekdays(){
CalculateWeekdays c = new CalculateWeekdays();
long result = c.getWorkingDaysWithoutStream(startTomorrow, endTomorrow);
assertEquals(0, result);
}
@Test
void givenAThreeWeekGapMidweekDates_whenUsingStreams_thenCalculateWeekdays(){
CalculateWeekdays c = new CalculateWeekdays();
long result = c.getWorkingDaysWithStream(startThreeWeeks, endThreeWeeks);
assertEquals(17, result);
}
@Test
void givenAThreeWeekGapMidweekDates_whenUsingMaths_thenCalculateWeekdays(){
CalculateWeekdays c = new CalculateWeekdays();
long result = c.getWorkingDaysWithoutStream(startThreeWeeks, endThreeWeeks);
assertEquals(17, result);
}
@Test
void givenThreeWeekGapMidweekAndWeekendDates_whenUsingStreams_thenCalculateWeekdays(){
CalculateWeekdays c = new CalculateWeekdays();
long result = c.getWorkingDaysWithStream(startThreeWeeksWeekend, endThreeWeeksWeekend);
assertEquals(5, result);
}
@Test
void givenThreeWeekGapMidweekAndWeekendDates_whenUsingMaths_thenCalculateWeekdays(){
CalculateWeekdays c = new CalculateWeekdays();
long result = c.getWorkingDaysWithoutStream(startThreeWeeksWeekend, endThreeWeeksWeekend);
assertEquals(5, result);
}
@Test
void givenThreeWeekGapWeekendDates_whenUsingStreams_thenCalculateWeekdays(){
CalculateWeekdays c = new CalculateWeekdays();
long result = c.getWorkingDaysWithStream(startThreeWeeks2, endThreeWeeks2);
assertEquals(40, result);
}
@Test
void givenThreeWeekGapWeekendDates_whenUsingMaths_thenCalculateWeekdays(){
CalculateWeekdays c = new CalculateWeekdays();
long result = c.getWorkingDaysWithoutStream(startThreeWeeks2, endThreeWeeks2);
assertEquals(40, result);
}
}
@@ -0,0 +1,74 @@
package com.baeldung.longtodate;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import org.joda.time.DateTimeZone;
import org.joda.time.Instant;
import org.junit.jupiter.api.Test;
class LongToDateUnitTest {
@Test
void givenLongValue_whenUsingInstantClass_thenConvert() {
Instant expectedDate = Instant.parse("2020-09-08T12:16:40Z");
long seconds = 1599567400L;
Instant date = Instant.ofEpochSecond(seconds);
assertEquals(expectedDate, date);
}
@Test
void givenLongValue_whenUsingLocalDateClass_thenConvert() {
LocalDate expectedDate = LocalDate.of(2023, 10, 17);
long epochDay = 19647L;
LocalDate date = LocalDate.ofEpochDay(epochDay);
assertEquals(expectedDate, date);
}
@Test
void givenLongValue_whenUsingDateClass_thenConvert() throws ParseException {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date expectedDate = dateFormat.parse("2023-07-15 22:00:00");
long milliseconds = 1689458400000L;
Date date = new Date(milliseconds);
assertEquals(expectedDate, date);
}
@Test
void givenLongValue_whenUsingCalendarClass_thenConvert() throws ParseException {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date expectedDate = dateFormat.parse("2023-07-15 22:00:00");
long milliseconds = 1689458400000L;
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
calendar.setTimeInMillis(milliseconds);
assertEquals(expectedDate, calendar.getTime());
}
@Test
void givenLongValue_whenUsingJodaTimeLocalDateClass_thenConvert() {
org.joda.time.LocalDate expectedDate = new org.joda.time.LocalDate(2023, 7, 15);
long milliseconds = 1689458400000L;
org.joda.time.LocalDate date = new org.joda.time.LocalDate(milliseconds, DateTimeZone.UTC);
assertEquals(expectedDate, date);
}
}
@@ -0,0 +1,6 @@
## Java Date/time conversion Cookbooks and Examples
This module contains articles about converting between Java date and time objects.
### Relevant Articles:
@@ -0,0 +1,57 @@
<?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-datetime-conversion-2</artifactId>
<version>${project.parent.version}</version>
<name>core-java-datetime-conversion-2</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>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${joda-time.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>com.github.msarhan</groupId>
<artifactId>ummalqura-calendar</artifactId>
<version>${ummalqura-calendar.version}</version>
</dependency>
</dependencies>
<build>
<finalName>core-java-datetime-conversion-2</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
</plugins>
</build>
<properties>
<joda-time.version>2.12.5</joda-time.version>
<ummalqura-calendar.version>2.0.2</ummalqura-calendar.version>
</properties>
</project>
@@ -12,3 +12,4 @@ This module contains articles about converting between Java date and time object
- [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 Long Timestamp to LocalDateTime in Java](https://www.baeldung.com/java-convert-long-timestamp-localdatetime)
- [Convert Joda-Time DateTime to Date and Vice Versa](https://www.baeldung.com/java-convert-joda-time-datetime-to-date)
@@ -25,12 +25,6 @@
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>com.github.msarhan</groupId>
<artifactId>ummalqura-calendar</artifactId>
<version>${ummalqura-calendar.version}</version>
</dependency>
</dependencies>
<build>
@@ -51,7 +45,6 @@
<properties>
<joda-time.version>2.12.5</joda-time.version>
<ummalqura-calendar.version>2.0.2</ummalqura-calendar.version>
</properties>
</project>
@@ -6,5 +6,6 @@ This module contains articles about core Java input and output (IO)
- [Get File Extension From MIME Type in Java](https://www.baeldung.com/java-mime-type-file-extension)
- [How to Remove Line Breaks From a File in Java](https://www.baeldung.com/java-file-remove-line-breaks)
- [Difference Between ZipFile and ZipInputStream in Java](https://www.baeldung.com/java-zipfile-vs-zipinputstream)
- [How to Write Strings to OutputStream in Java](https://www.baeldung.com/java-write-string-outputstream)
- [[<-- Prev]](/core-java-modules/core-java-io-4)
@@ -9,3 +9,5 @@ This module contains articles about core Java input/output(IO) APIs.
- [Converting Relative to Absolute Paths in Java](https://www.baeldung.com/java-from-relative-to-absolute-paths)
- [Detect EOF in Java](https://www.baeldung.com/java-file-detect-end-of-file)
- [PrintWriter vs. FileWriter in Java](https://www.baeldung.com/java-printwriter-filewriter-difference)
- [Read Input Character-by-Character in Java](https://www.baeldung.com/java-read-input-character)
- [Difference Between flush() and close() in Java FileWriter](https://www.baeldung.com/java-filewriter-flush-vs-close)
@@ -0,0 +1,7 @@
FROM maven:3.9-amazoncorretto-17
WORKDIR /app
COPY /src/test/java/com/baeldung/setenvironment/SettingDockerEnvironmentVariableUnitTest.java \
./src/test/java/com/baeldung/setenvironment/
COPY /docker-pom.xml ./
ENV CUSTOM_DOCKER_ENV_VARIABLE=TRUE
ENTRYPOINT mvn -f docker-pom.xml test
@@ -10,4 +10,6 @@ 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)
- [Compress and Uncompress Byte Array Using Deflater/Inflater](https://www.baeldung.com/java-compress-uncompress-byte-array)
- [Static Final Variables in Java](https://www.baeldung.com/java-static-final-variables)
- [What Is the Error: “Non-static method cannot be referenced from a static context”?](https://www.baeldung.com/java-non-static-method-cannot-be-referenced-from-a-static-context)
@@ -0,0 +1,42 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-lang-6</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers</artifactId>
<version>${testcontainers.junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${testcontainers.junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.10.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.10.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<testcontainers.junit.version>1.19.3</testcontainers.junit.version>
</properties>
</project>
@@ -33,6 +33,25 @@
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh.version}</version>
</dependency>
<dependency>
<groupId>org.junit-pioneer</groupId>
<artifactId>junit-pioneer</artifactId>
<version>${junit.pioneer.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers</artifactId>
<version>${testcontaienr.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${testcontaienr.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
@@ -53,6 +72,8 @@
<version>${jmh.version}</version>
</path>
</annotationProcessorPaths>
<source>14</source>
<target>14</target>
</configuration>
</plugin>
</plugins>
@@ -61,6 +82,8 @@
<properties>
<mapstruct.version>1.6.0.Beta1</mapstruct.version>
<jmh.version>1.37</jmh.version>
<junit.pioneer.version>2.2.0</junit.pioneer.version>
<testcontaienr.version>1.19.3</testcontaienr.version>
</properties>
</project>

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