Merge branch 'eugenp:master' into master
This commit is contained in:
+8
-10
@@ -1,23 +1,22 @@
|
||||
package com.baeldung.algorithms.mergeintervals;
|
||||
|
||||
import static java.lang.Integer.max;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
|
||||
public class MergeOverlappingIntervals {
|
||||
|
||||
public List<Interval> doMerge(List<Interval> intervals) {
|
||||
// Sort the intervals based on start time
|
||||
intervals.sort((one, two) -> one.start - two.start);
|
||||
|
||||
// Create somewhere to put the merged list, start it off with the earliest starting interval
|
||||
intervals.sort(Comparator.comparingInt(interval -> interval.start));
|
||||
ArrayList<Interval> merged = new ArrayList<>();
|
||||
merged.add(intervals.get(0));
|
||||
|
||||
// Loop over each interval and merge if start time is before the end time of the
|
||||
// previous interval
|
||||
intervals.forEach(interval -> {
|
||||
if (merged.get(merged.size() - 1).end > interval.start) {
|
||||
merged.get(merged.size() - 1).setEnd(interval.end);
|
||||
Interval lastMerged = merged.get(merged.size() - 1);
|
||||
if (interval.start <= lastMerged.end){
|
||||
lastMerged.setEnd(max(interval.end, lastMerged.end));
|
||||
} else {
|
||||
merged.add(interval);
|
||||
}
|
||||
@@ -25,5 +24,4 @@ public class MergeOverlappingIntervals {
|
||||
|
||||
return merged;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
+20
-12
@@ -1,30 +1,38 @@
|
||||
package com.baeldung.algorithms.mergeintervals;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class MergeIntervalsUnitTest {
|
||||
|
||||
private ArrayList<Interval> intervals = new ArrayList<>(Arrays.asList(
|
||||
new Interval(2, 5),
|
||||
new Interval(13, 20),
|
||||
new Interval(11, 15),
|
||||
new Interval(1, 3)
|
||||
private List<Interval> intervals = new ArrayList<>(Arrays.asList(
|
||||
// @formatter:off
|
||||
new Interval(3, 5),
|
||||
new Interval(13, 20),
|
||||
new Interval(11, 15),
|
||||
new Interval(15, 16),
|
||||
new Interval(1, 3),
|
||||
new Interval(4, 5),
|
||||
new Interval(16, 17)
|
||||
// @formatter:on
|
||||
));
|
||||
private ArrayList<Interval> intervalsMerged = new ArrayList<>(Arrays.asList(
|
||||
new Interval(1, 5),
|
||||
new Interval(11, 20)
|
||||
private List<Interval> intervalsMerged = new ArrayList<>(Arrays.asList(
|
||||
// @formatter:off
|
||||
new Interval(1, 5),
|
||||
new Interval(11, 20)
|
||||
// @formatter:on
|
||||
));
|
||||
|
||||
@Test
|
||||
void givenIntervals_whenMerging_thenReturnMergedIntervals() {
|
||||
MergeOverlappingIntervals merger = new MergeOverlappingIntervals();
|
||||
ArrayList<Interval> result = (ArrayList<Interval>) merger.doMerge(intervals);
|
||||
assertArrayEquals(intervalsMerged.toArray(), result.toArray());
|
||||
List<Interval> result = merger.doMerge(intervals);
|
||||
assertEquals(intervalsMerged, result);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -3,3 +3,4 @@
|
||||
- [Find the Equilibrium Indexes of an Array in Java](https://www.baeldung.com/java-equilibrium-index-array)
|
||||
- [Moves Zeros to the End of an Array in Java](https://www.baeldung.com/java-array-sort-move-zeros-end)
|
||||
- [Finding the Majority Element of an Array in Java](https://www.baeldung.com/java-array-find-majority-element)
|
||||
- [Set Matrix Elements to Zero in Java](https://www.baeldung.com/java-set-matrix-elements-to-zero)
|
||||
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
package com.baeldung.matrixtozero;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class SetMatrixToZero{
|
||||
static void setZeroesByNaiveApproach(int[][] matrix) {
|
||||
int row = matrix.length;
|
||||
int col = matrix[0].length;
|
||||
int [][] result = new int[row][col];
|
||||
|
||||
for(int i = 0; i<row; i++){
|
||||
for(int j = 0; j < col; j++){
|
||||
result[i][j] = matrix[i][j];
|
||||
}
|
||||
}
|
||||
|
||||
for(int i = 0; i < row; i++){
|
||||
for(int j = 0; j < col; j++){
|
||||
if(matrix[i][j] == 0){
|
||||
for(int k = 0; k < col; k++){
|
||||
result[i][k] = 0;
|
||||
}
|
||||
for(int k = 0; k < row; k++){
|
||||
result[k][j] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for(int i = 0; i < row; i++){
|
||||
for(int j = 0; j < col; j++){
|
||||
matrix[i][j] = result[i][j];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void setZeroesByTimeOptimizedApproach(int[][] matrix) {
|
||||
int rows = matrix.length;
|
||||
int cols = matrix[0].length;
|
||||
|
||||
Set<Integer> rowSet = new HashSet<>();
|
||||
Set<Integer> colSet = new HashSet<>();
|
||||
|
||||
for(int i = 0; i < rows; i++){
|
||||
for(int j = 0; j < cols; j++){
|
||||
if (matrix[i][j] == 0){
|
||||
rowSet.add(i);
|
||||
colSet.add(j);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for(int row: rowSet){
|
||||
for(int j = 0; j < cols; j++){
|
||||
matrix[row][j] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
for(int col: colSet) {
|
||||
for(int i = 0; i < rows; i++){
|
||||
matrix[i][col] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static boolean hasZeroInFirstRow(int[][] matrix, int cols) {
|
||||
for (int j = 0; j < cols; j++) {
|
||||
if (matrix[0][j] == 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static boolean hasZeroInFirstCol(int[][] matrix, int rows) {
|
||||
for (int i = 0; i < rows; i++) {
|
||||
if (matrix[i][0] == 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static void markZeroesInMatrix(int[][] matrix, int rows, int cols) {
|
||||
for (int i = 1; i < rows; i++) {
|
||||
for (int j = 1; j < cols; j++) {
|
||||
if (matrix[i][j] == 0) {
|
||||
matrix[i][0] = 0;
|
||||
matrix[0][j] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void setZeroesInRows(int[][] matrix, int rows, int cols) {
|
||||
for (int i = 1; i < rows; i++) {
|
||||
if (matrix[i][0] == 0) {
|
||||
for (int j = 1; j < cols; j++) {
|
||||
matrix[i][j] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void setZeroesInCols(int[][] matrix, int rows, int cols) {
|
||||
for (int j = 1; j < cols; j++) {
|
||||
if (matrix[0][j] == 0) {
|
||||
for (int i = 1; i < rows; i++) {
|
||||
matrix[i][j] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void setZeroesInFirstRow(int[][] matrix, int cols) {
|
||||
for (int j = 0; j < cols; j++) {
|
||||
matrix[0][j] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
static void setZeroesInFirstCol(int[][] matrix, int rows) {
|
||||
for (int i = 0; i < rows; i++) {
|
||||
matrix[i][0] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
static void setZeroesByOptimalApproach(int[][] matrix) {
|
||||
int rows = matrix.length;
|
||||
int cols = matrix[0].length;
|
||||
|
||||
boolean firstRowZero = hasZeroInFirstRow(matrix, cols);
|
||||
boolean firstColZero = hasZeroInFirstCol(matrix, rows);
|
||||
|
||||
markZeroesInMatrix(matrix, rows, cols);
|
||||
|
||||
setZeroesInRows(matrix, rows, cols);
|
||||
setZeroesInCols(matrix, rows, cols);
|
||||
|
||||
if (firstRowZero) {
|
||||
setZeroesInFirstRow(matrix, cols);
|
||||
}
|
||||
if (firstColZero) {
|
||||
setZeroesInFirstCol(matrix, rows);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
package com.baeldung.matrixtozero;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class SetMatrixToZeroUnitTest{
|
||||
@Test
|
||||
void givenMatrix_whenUsingSetZeroesByNaiveApproach_thenSetZeroes() {
|
||||
int[][] matrix = {
|
||||
{1, 2, 3},
|
||||
{4, 0, 6},
|
||||
{7, 8, 9}
|
||||
};
|
||||
int[][] expected = {
|
||||
{1, 0, 3},
|
||||
{0, 0, 0},
|
||||
{7, 0, 9}
|
||||
};
|
||||
SetMatrixToZero.setZeroesByNaiveApproach(matrix);
|
||||
assertArrayEquals(expected, matrix);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMatrix_whenUsingSetZeroesByTimeOptimizedApproach_thenSetZeroes() {
|
||||
int[][] matrix = {
|
||||
{1, 2, 3},
|
||||
{4, 0, 6},
|
||||
{7, 8, 9}
|
||||
};
|
||||
int[][] expected = {
|
||||
{1, 0, 3},
|
||||
{0, 0, 0},
|
||||
{7, 0, 9}
|
||||
};
|
||||
SetMatrixToZero.setZeroesByTimeOptimizedApproach(matrix);
|
||||
assertArrayEquals(expected, matrix);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMatrix_whenUsingSetZeroesByOptimalApproach_thenSetZeroes() {
|
||||
int[][] matrix = {
|
||||
{1, 2, 3},
|
||||
{4, 0, 6},
|
||||
{7, 8, 9}
|
||||
};
|
||||
int[][] expected = {
|
||||
{1, 0, 3},
|
||||
{0, 0, 0},
|
||||
{7, 0, 9}
|
||||
};
|
||||
SetMatrixToZero.setZeroesByOptimalApproach(matrix);
|
||||
assertArrayEquals(expected, matrix);
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.printnullvalues;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
public class Employee {
|
||||
private String name;
|
||||
private int age;
|
||||
private String department;
|
||||
|
||||
public Employee(String name, int age, String department) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
this.department = department;
|
||||
}
|
||||
|
||||
public String toStringUsingNullCheck() {
|
||||
return "Name: " + (name != null ? name : "Unknown") +
|
||||
", Age: " + age +
|
||||
", Department: " + (department != null ? department : "Unknown");
|
||||
}
|
||||
|
||||
public String toStringUsingOptional() {
|
||||
return "Name: " + Optional.ofNullable(name).orElse("Unknown") +
|
||||
", Age: " + age +
|
||||
", Department: " + Optional.ofNullable(department).orElse("Unknown");
|
||||
}
|
||||
|
||||
private String getDefaultIfNull(String value, String defaultValue) {
|
||||
return value != null ? value : defaultValue;
|
||||
}
|
||||
|
||||
public String toStringUsingCustomHelper() {
|
||||
return "Name: " + getDefaultIfNull(name, "Unknown") +
|
||||
", Age: " + age +
|
||||
", Department: " + getDefaultIfNull(department, "Unknown");
|
||||
}
|
||||
|
||||
public String toStringUsingObjects() {
|
||||
return "Name: " + Objects.toString(name, "Unknown") +
|
||||
", Age: " + age +
|
||||
", Department: " + Objects.toString(department, "Unknown");
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.printnullvalues;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class PrintingNullValuesUnitTest {
|
||||
Employee employee = new Employee(null, 30, null);
|
||||
String expected = "Name: Unknown, Age: 30, Department: Unknown";
|
||||
|
||||
@Test
|
||||
public void givenNullValues_whenToStringUsingNullCheck_thenCorrectStringReturned() {
|
||||
assertEquals(expected, employee.toStringUsingNullCheck());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNullValues_whenToStringUsingOptional_thenCorrectStringReturned() {
|
||||
assertEquals(expected, employee.toStringUsingOptional());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNullValues_whenToStringUsingCustomHelper_thenCorrectStringReturned() {
|
||||
assertEquals(expected, employee.toStringUsingCustomHelper());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNullValues_whenToStringUsingObjects_thenCorrectStringReturned() {
|
||||
assertEquals(expected, employee.toStringUsingObjects());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
## Relevant Articles:
|
||||
- [[<-- Prev]](/core-java-modules/core-java-networking-4)
|
||||
@@ -0,0 +1,59 @@
|
||||
<?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-networking-5</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
<name>core-java-networking-5</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>commons-validator</groupId>
|
||||
<artifactId>commons-validator</artifactId>
|
||||
<version>${commons-validator.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jsoup</groupId>
|
||||
<artifactId>jsoup</artifactId>
|
||||
<version>${jsoup.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpclient</artifactId>
|
||||
<version>${httpclient.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.ws.rs</groupId>
|
||||
<artifactId>javax.ws.rs-api</artifactId>
|
||||
<version>${javax.ws.rs-api.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.glassfish.jersey.core</groupId>
|
||||
<artifactId>jersey-common</artifactId>
|
||||
<version>${jersey-common.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-web</artifactId>
|
||||
<version>${spring-web.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<commons-validator.version>1.7</commons-validator.version>
|
||||
<jsoup.version>1.17.2</jsoup.version>
|
||||
<httpclient.version>4.5.2</httpclient.version>
|
||||
<javax.ws.rs-api.version>2.1.1</javax.ws.rs-api.version>
|
||||
<jersey-common.version>2.22.2</jersey-common.version>
|
||||
<spring-web.version>6.0.6</spring-web.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
package com.baeldung.redirectedurl;
|
||||
|
||||
import org.apache.http.client.config.RequestConfig;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class RedirectedUrlUnitTest {
|
||||
String canonicalUrl = "http://www.baeldung.com/";
|
||||
String expectedRedirectedUrl = "https://www.baeldung.com/";
|
||||
|
||||
@Test
|
||||
public void givenOriginalUrl_whenFindRedirectUrlUsingHttpURLConnection_thenCorrectRedirectedUrlReturned() throws IOException {
|
||||
URL url = new URL(canonicalUrl);
|
||||
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
|
||||
connection.setInstanceFollowRedirects(true);
|
||||
int status = connection.getResponseCode();
|
||||
String redirectedUrl = null;
|
||||
if (status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_MOVED_TEMP) {
|
||||
redirectedUrl = connection.getHeaderField("Location");
|
||||
}
|
||||
connection.disconnect();
|
||||
assertEquals(expectedRedirectedUrl, redirectedUrl);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOriginalUrl_whenFindRedirectUrlUsingHttpClient_thenCorrectRedirectedUrlReturned() throws IOException {
|
||||
RequestConfig config = RequestConfig.custom()
|
||||
.setRedirectsEnabled(false)
|
||||
.build();
|
||||
try (CloseableHttpClient httpClient = HttpClients.custom()
|
||||
.setDefaultRequestConfig(config)
|
||||
.build()) {
|
||||
HttpGet httpGet = new HttpGet(canonicalUrl);
|
||||
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
|
||||
int statusCode = response.getStatusLine().getStatusCode();
|
||||
String redirectedUrl = null;
|
||||
if (statusCode == HttpURLConnection.HTTP_MOVED_PERM || statusCode == HttpURLConnection.HTTP_MOVED_TEMP) {
|
||||
org.apache.http.Header[] headers = response.getHeaders("Location");
|
||||
if (headers.length > 0) {
|
||||
redirectedUrl = headers[0].getValue();
|
||||
}
|
||||
}
|
||||
assertEquals(expectedRedirectedUrl, redirectedUrl);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -165,6 +165,7 @@
|
||||
<module>core-java-networking</module>
|
||||
<module>core-java-networking-2</module>
|
||||
<module>core-java-networking-4</module>
|
||||
<module>core-java-networking-5</module>
|
||||
<module>core-java-nio</module>
|
||||
<module>core-java-nio-2</module>
|
||||
<module>core-java-numbers</module>
|
||||
|
||||
@@ -49,11 +49,23 @@
|
||||
|
||||
<properties>
|
||||
<jool.version>0.9.12</jool.version>
|
||||
<parallel-collectors.version>2.6.0</parallel-collectors.version>
|
||||
<parallel-collectors.version>3.0.0</parallel-collectors.version>
|
||||
<vavr.version>0.9.0</vavr.version>
|
||||
<eclipse-collections.version>8.2.0</eclipse-collections.version>
|
||||
<streamex.version>0.8.1</streamex.version>
|
||||
<protonpack.version>1.15</protonpack.version>
|
||||
</properties>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>21</source>
|
||||
<target>21</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
package com.baeldung.parallel_collectors;
|
||||
|
||||
import com.pivovarit.collectors.ParallelCollectors;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static java.util.stream.Collectors.toList;
|
||||
|
||||
public class ParallelCollectorsVirtualThreadsManualTest {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(ParallelCollectorsVirtualThreadsManualTest.class);
|
||||
|
||||
// increase the number of parallel processes to find the max number of threads on your machine
|
||||
@Test
|
||||
public void givenParallelism_whenUsingOSThreads_thenShouldRunOutOfThreads() {
|
||||
int parallelProcesses = 50_000;
|
||||
|
||||
var e = Executors.newFixedThreadPool(parallelProcesses);
|
||||
|
||||
var result = timed(() -> Stream.iterate(0, i -> i + 1).limit(parallelProcesses)
|
||||
.collect(ParallelCollectors.parallel(i -> fetchById(i), toList(), e, parallelProcesses))
|
||||
.join());
|
||||
|
||||
log.info("{}", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenParallelism_whenUsingVThreads_thenShouldProcessInParallel() {
|
||||
int parallelProcesses = 1000_000;
|
||||
|
||||
var result = timed(() -> Stream.iterate(0, i -> i + 1).limit(parallelProcesses)
|
||||
.collect(ParallelCollectors.parallel(i -> fetchById(i), toList()))
|
||||
.join());
|
||||
|
||||
log.info("{}", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenParallelismAndPCollectors2_whenUsingVThreads_thenShouldProcessInParallel() {
|
||||
int parallelProcesses = 1000_000;
|
||||
|
||||
var result = timed(() -> Stream.iterate(0, i -> i + 1).limit(parallelProcesses)
|
||||
.collect(ParallelCollectors.parallel(i -> fetchById(i), toList(), Executors.newVirtualThreadPerTaskExecutor(), Integer.MAX_VALUE))
|
||||
.join());
|
||||
|
||||
log.info("{}", result);
|
||||
}
|
||||
|
||||
private static String fetchById(int id) {
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException e) {
|
||||
// ignore shamelessly
|
||||
}
|
||||
|
||||
return "user-" + id;
|
||||
}
|
||||
|
||||
private static <T> T timed(Supplier<T> supplier) {
|
||||
var before = Instant.now();
|
||||
T result = supplier.get();
|
||||
var after = Instant.now();
|
||||
log.info("Execution time: {} ms", Duration.between(before, after).toMillis());
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -34,7 +34,7 @@
|
||||
<dependency>
|
||||
<groupId>org.springdoc</groupId>
|
||||
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
|
||||
<version>${spring.webmvc.version}</version>
|
||||
<version>${springdoc-openapi-webmvc-ui.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
@@ -71,6 +71,7 @@
|
||||
<java.version>17</java.version>
|
||||
<conductor.client.version>2.0.8</conductor.client.version>
|
||||
<spring.webmvc.version>2.1.0</spring.webmvc.version>
|
||||
<springdoc-openapi-webmvc-ui.version>2.5.0</springdoc-openapi-webmvc-ui.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
@@ -19,10 +19,15 @@
|
||||
<version>${mockito-inline.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>1.18.32</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<mockito-inline.version>5.2.0</mockito-inline.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
</project>
|
||||
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.builder.implementation;
|
||||
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public class GenericBuilder<T> {
|
||||
|
||||
private final Supplier<T> supplier;
|
||||
|
||||
private GenericBuilder(Supplier<T> supplier) {
|
||||
this.supplier = supplier;
|
||||
}
|
||||
|
||||
public static <T> GenericBuilder<T> of(Supplier<T> supplier) {
|
||||
return new GenericBuilder<>(supplier);
|
||||
}
|
||||
|
||||
public <P> GenericBuilder<T> with(BiConsumer<T, P> consumer, P value) {
|
||||
return new GenericBuilder<>(() -> {
|
||||
T object = supplier.get();
|
||||
consumer.accept(object, value);
|
||||
return object;
|
||||
});
|
||||
}
|
||||
|
||||
public T build() {
|
||||
return supplier.get();
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.builder.implementation;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Builder
|
||||
@Getter
|
||||
@Setter
|
||||
public class LombokPost {
|
||||
|
||||
private String title;
|
||||
|
||||
private String text;
|
||||
|
||||
private String category;
|
||||
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package com.baeldung.builder.implementation;
|
||||
|
||||
public class Post {
|
||||
|
||||
private String title;
|
||||
|
||||
private String text;
|
||||
|
||||
private String category;
|
||||
|
||||
Post(Builder builder) {
|
||||
this.title = builder.title;
|
||||
this.text = builder.text;
|
||||
this.category = builder.category;
|
||||
}
|
||||
|
||||
Post() {}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public String getText() {
|
||||
return text;
|
||||
}
|
||||
|
||||
public String getCategory() {
|
||||
return category;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public void setText(String text) {
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
public void setCategory(String category) {
|
||||
this.category = category;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Post{" + "title='" + title + '\'' + ", text='" + text + '\'' + ", category='" + category + '\'' + '}';
|
||||
}
|
||||
|
||||
public static class Builder {
|
||||
private String title;
|
||||
private String text;
|
||||
private String category;
|
||||
|
||||
public Builder() {}
|
||||
|
||||
public Builder title(String title) {
|
||||
this.title = title;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder text(String text) {
|
||||
this.text = text;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder category(String category) {
|
||||
this.category = category;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Post build() {
|
||||
return new Post(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package com.baeldung.builder.implementation;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class BuilderImplementationUnitTest {
|
||||
|
||||
@Test
|
||||
void givenClassicBuilder_whenBuild_thenReturnObject() {
|
||||
|
||||
Post post = new Post.Builder()
|
||||
.title("Java Builder Pattern")
|
||||
.text("Explaining how to implement the Builder Pattern in Java")
|
||||
.category("Programming")
|
||||
.build();
|
||||
|
||||
assertEquals("Java Builder Pattern", post.getTitle());
|
||||
assertEquals("Explaining how to implement the Builder Pattern in Java", post.getText());
|
||||
assertEquals("Programming", post.getCategory());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenGenericBuilder_whenBuild_thenReturnObject() {
|
||||
|
||||
Post post = GenericBuilder.of(Post::new)
|
||||
.with(Post::setTitle, "Java Builder Pattern")
|
||||
.with(Post::setText, "Explaining how to implement the Builder Pattern in Java")
|
||||
.with(Post::setCategory, "Programming")
|
||||
.build();
|
||||
|
||||
assertEquals("Java Builder Pattern", post.getTitle());
|
||||
assertEquals("Explaining how to implement the Builder Pattern in Java", post.getText());
|
||||
assertEquals("Programming", post.getCategory());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenLombokBuilder_whenBuild_thenReturnObject() {
|
||||
|
||||
LombokPost post = LombokPost.builder()
|
||||
.title("Java Builder Pattern")
|
||||
.text("Explaining how to implement the Builder Pattern in Java")
|
||||
.category("Programming")
|
||||
.build();
|
||||
|
||||
assertEquals("Java Builder Pattern", post.getTitle());
|
||||
assertEquals("Explaining how to implement the Builder Pattern in Java", post.getText());
|
||||
assertEquals("Programming", post.getCategory());
|
||||
}
|
||||
}
|
||||
@@ -69,6 +69,7 @@
|
||||
<module>spring-boot-persistence-mongodb</module>
|
||||
<module>spring-boot-persistence-mongodb-2</module>
|
||||
<module>spring-boot-persistence-mongodb-3</module>
|
||||
<module>spring-boot-persistence-mongodb-4</module>
|
||||
<module>spring-data-arangodb</module>
|
||||
<!--<module>spring-data-cassandra</module>--> <!-- failing after upgrading to jdk17. JDK 17 compatibility in progress CASSANDRA-16895 -->
|
||||
<module>spring-data-cassandra-test</module>
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
# Relevant Articles
|
||||
|
||||
- [ZonedDateTime with Spring Data MongoDB](https://www.baeldung.com/spring-data-mongodb-zoneddatetime)
|
||||
- [A Guide to @DBRef in MongoDB](https://www.baeldung.com/spring-mongodb-dbref-annotation)
|
||||
- More articles: [[<--prev]](../spring-boot-persistence-mongodb-3)
|
||||
@@ -0,0 +1,34 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>spring-boot-persistence-mongodb-4</artifactId>
|
||||
<name>spring-boot-persistence-mongodb-4</name>
|
||||
<description>This is simple boot application for Spring boot persistence mongodb test</description>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-boot-2</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-boot-2</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<!-- MongoDB -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-mongodb</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>de.flapdoodle.embed</groupId>
|
||||
<artifactId>de.flapdoodle.embed.mongo</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
+1
-2
@@ -1,5 +1,6 @@
|
||||
package com.baeldung.mongodb.dbref;
|
||||
|
||||
import com.baeldung.mongodb.dbref.repository.PersonRepository;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
@@ -7,8 +8,6 @@ import org.springframework.boot.ApplicationArguments;
|
||||
import org.springframework.boot.ApplicationRunner;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.baeldung.mongodb.dbref.repository.PersonRepository;
|
||||
|
||||
@Component
|
||||
public class DbRefTester implements ApplicationRunner {
|
||||
|
||||
+2
-2
@@ -1,11 +1,11 @@
|
||||
package com.baeldung.mongodb.dbref.model;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.annotation.Id;
|
||||
import org.springframework.data.mongodb.core.mapping.DBRef;
|
||||
import org.springframework.data.mongodb.core.mapping.Document;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Document(collection = "Person")
|
||||
public class Person {
|
||||
|
||||
+1
-2
@@ -1,8 +1,7 @@
|
||||
package com.baeldung.mongodb.dbref.repository;
|
||||
|
||||
import org.springframework.data.mongodb.repository.MongoRepository;
|
||||
|
||||
import com.baeldung.mongodb.dbref.model.Person;
|
||||
import org.springframework.data.mongodb.repository.MongoRepository;
|
||||
|
||||
public interface PersonRepository extends MongoRepository<Person, String> {
|
||||
|
||||
+4
-5
@@ -1,15 +1,14 @@
|
||||
package com.baeldung.zoneddatetime.config;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import com.baeldung.zoneddatetime.converter.ZonedDateTimeReadConverter;
|
||||
import com.baeldung.zoneddatetime.converter.ZonedDateTimeWriteConverter;
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
import org.springframework.data.mongodb.config.AbstractMongoClientConfiguration;
|
||||
import org.springframework.data.mongodb.core.convert.MongoCustomConversions;
|
||||
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
|
||||
|
||||
import com.baeldung.zoneddatetime.converter.ZonedDateTimeReadConverter;
|
||||
import com.baeldung.zoneddatetime.converter.ZonedDateTimeWriteConverter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@EnableMongoRepositories(basePackages = { "com.baeldung" })
|
||||
public class MongoConfig extends AbstractMongoClientConfiguration {
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user