Merge branch 'eugenp:master' into JAVA-20167_1

This commit is contained in:
timis1 2023-06-12 01:52:08 +03:00 committed by GitHub
commit 3b49a56372
304 changed files with 3868 additions and 750 deletions

View File

@ -10,7 +10,7 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
- [Converting Between Roman and Arabic Numerals in Java](https://www.baeldung.com/java-convert-roman-arabic)
- [Practical Java Examples of the Big O Notation](https://www.baeldung.com/java-algorithm-complexity)
- [Checking If a List Is Sorted in Java](https://www.baeldung.com/java-check-if-list-sorted)
- [Checking if a Java Graph has a Cycle](https://www.baeldung.com/java-graph-has-a-cycle)
- [Checking if a Java Graph Has a Cycle](https://www.baeldung.com/java-graph-has-a-cycle)
- [A Guide to the Folding Technique in Java](https://www.baeldung.com/folding-hashing-technique)
- [Creating a Triangle with for Loops in Java](https://www.baeldung.com/java-print-triangle)
- [The K-Means Clustering Algorithm in Java](https://www.baeldung.com/java-k-means-clustering-algorithm)

View File

@ -5,10 +5,10 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
### Relevant articles:
- [Multi-Swarm Optimization Algorithm in Java](https://www.baeldung.com/java-multi-swarm-algorithm)
- [Check If a String Contains All The Letters of The Alphabet with Java](https://www.baeldung.com/java-string-contains-all-letters)
- [Check if a String Contains All the Letters of the Alphabet With Java](https://www.baeldung.com/java-string-contains-all-letters)
- [Find the Middle Element of a Linked List in Java](https://www.baeldung.com/java-linked-list-middle-element)
- [Find Substrings That Are Palindromes in Java](https://www.baeldung.com/java-palindrome-substrings)
- [Find the Longest Substring without Repeating Characters](https://www.baeldung.com/java-longest-substring-without-repeated-characters)
- [Find the Longest Substring Without Repeating Characters](https://www.baeldung.com/java-longest-substring-without-repeated-characters)
- [Permutations of an Array in Java](https://www.baeldung.com/java-array-permutations)
- [Find the Smallest Missing Integer in an Array](https://www.baeldung.com/java-smallest-missing-integer-in-array)
- [Permutations of a String in Java](https://www.baeldung.com/java-string-permutations)

View File

@ -9,7 +9,7 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
- [Reversing a Binary Tree in Java](https://www.baeldung.com/java-reversing-a-binary-tree)
- [Find If Two Numbers Are Relatively Prime in Java](https://www.baeldung.com/java-two-relatively-prime-numbers)
- [Knapsack Problem Implementation in Java](https://www.baeldung.com/java-knapsack)
- [How to Determine if a Binary Tree is Balanced in Java](https://www.baeldung.com/java-balanced-binary-tree)
- [How to Determine if a Binary Tree Is Balanced in Java](https://www.baeldung.com/java-balanced-binary-tree)
- [Overview of Combinatorial Problems in Java](https://www.baeldung.com/java-combinatorial-algorithms)
- [Prims Algorithm with a Java Implementation](https://www.baeldung.com/java-prim-algorithm)
- [Maximum Subarray Problem in Java](https://www.baeldung.com/java-maximum-subarray)

View File

@ -1,3 +1,3 @@
### Relevant Articles:
- [Server-Sent Events (SSE) In JAX-RS](https://www.baeldung.com/java-ee-jax-rs-sse)
- [Server-Sent Events (SSE) in JAX-RS](https://www.baeldung.com/java-ee-jax-rs-sse)

View File

@ -13,5 +13,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [How To Get Cookies From the Apache HttpClient Response](https://www.baeldung.com/java-apache-httpclient-cookies)
- [Enabling Logging for Apache HttpClient](https://www.baeldung.com/apache-httpclient-enable-logging)
- [Apache HttpClient vs. CloseableHttpClient](https://www.baeldung.com/apache-httpclient-vs-closeablehttpclient)
- [Expand Shortened URLs with Apache HttpClient](https://www.baeldung.com/apache-httpclient-expand-url)
- More articles: [[<-- prev]](../apache-httpclient)

View File

@ -8,7 +8,7 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant Articles:
- [Apache HttpClient Cancel Request](https://www.baeldung.com/httpclient-cancel-request)
- [Apache HttpClient 4 Cookbook](https://www.baeldung.com/httpclient4)
- [Apache HttpClient Cookbook](https://www.baeldung.com/apache-httpclient-cookbook)
- [Apache HttpClient Follow Redirects for POST](https://www.baeldung.com/httpclient-redirect-on-http-post)
- [Multipart Upload with Apache HttpClient](https://www.baeldung.com/httpclient-multipart-upload)
- [Apache HttpAsyncClient Tutorial](https://www.baeldung.com/httpasyncclient-tutorial)

View File

@ -21,7 +21,7 @@ public class GetRequestMockServer {
public static String serviceOneUrl;
public static String serviceTwoUrl;
private static int serverPort;
public static int serverPort;
public static final String SERVER_ADDRESS = "127.0.0.1";
public static final String PATH_ONE = "/test1";
@ -29,9 +29,8 @@ public class GetRequestMockServer {
public static final String METHOD = "GET";
@BeforeAll
static void startServer() throws IOException, URISyntaxException {
//serverPort = getFreePort();
serverPort = 8080;
static void startServer() throws IOException {
serverPort = getFreePort();
System.out.println("Free port "+serverPort);
serviceOneUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH_ONE;
serviceTwoUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH_TWO;

View File

@ -9,6 +9,7 @@ import java.util.concurrent.Future;
import javax.net.ssl.SSLContext;
import org.apache.hc.client5.http.impl.routing.DefaultProxyRoutePlanner;
import org.junit.jupiter.api.Test;
import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
@ -55,12 +56,12 @@ class HttpAsyncClientLiveTest extends GetRequestMockServer {
@Test
void whenUseHttpAsyncClient_thenCorrect() throws InterruptedException, ExecutionException, IOException {
final HttpHost target = new HttpHost(HOST);
final HttpHost target = new HttpHost(HOST_WITH_COOKIE);
final SimpleHttpRequest request = SimpleRequestBuilder.get()
.setHttpHost(target)
.build();
final CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
final CloseableHttpAsyncClient client = HttpAsyncClients.custom().build();
client.start();
@ -102,30 +103,15 @@ class HttpAsyncClientLiveTest extends GetRequestMockServer {
@Test
void whenUseProxyWithHttpClient_thenCorrect() throws Exception {
final CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
final HttpHost proxy = new HttpHost("127.0.0.1", GetRequestMockServer.serverPort);
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
final CloseableHttpAsyncClient client = HttpAsyncClients.custom()
.setRoutePlanner(routePlanner)
.build();
client.start();
final HttpHost proxy = new HttpHost("127.0.0.1", 8080);
final RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
final SimpleHttpRequest request = new SimpleHttpRequest("GET" ,HOST_WITH_PROXY);
request.setConfig(config);
final Future<SimpleHttpResponse> future = client.execute(request, new FutureCallback<>(){
@Override
public void completed(SimpleHttpResponse response) {
System.out.println("responseData");
}
@Override
public void failed(Exception ex) {
System.out.println("Error executing HTTP request: " + ex.getMessage());
}
@Override
public void cancelled() {
System.out.println("HTTP request execution cancelled");
}
});
final Future<SimpleHttpResponse> future = client.execute(request, null);
final HttpResponse response = future.get();
assertThat(response.getCode(), equalTo(200));
client.close();

View File

@ -0,0 +1,77 @@
package com.baeldung.httpclient;
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
import static org.mockserver.matchers.Times.exactly;
import static org.mockserver.model.HttpRequest.request;
import static org.mockserver.model.HttpResponse.response;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.URISyntaxException;
import org.apache.http.HttpStatus;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.mockserver.client.MockServerClient;
import org.mockserver.integration.ClientAndServer;
public class GetRequestMockServer {
public static ClientAndServer mockServer;
public static String serviceOneUrl;
public static String serviceTwoUrl;
public static int serverPort;
public static final String SERVER_ADDRESS = "127.0.0.1";
public static final String PATH_ONE = "/test1";
public static final String PATH_TWO = "/test2";
public static final String METHOD = "GET";
@BeforeAll
static void startServer() throws IOException, URISyntaxException {
serverPort = getFreePort();
serviceOneUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH_ONE;
serviceTwoUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH_TWO;
mockServer = startClientAndServer(serverPort);
mockGetRequest();
}
@AfterAll
static void stopServer() {
mockServer.stop();
}
private static void mockGetRequest() {
new MockServerClient(SERVER_ADDRESS, serverPort)
.when(
request()
.withPath(PATH_ONE)
.withMethod(METHOD),
exactly(5)
)
.respond(
response()
.withStatusCode(HttpStatus.SC_OK)
.withBody("{\"status\":\"ok\"}")
);
new MockServerClient(SERVER_ADDRESS, serverPort)
.when(
request()
.withPath(PATH_TWO)
.withMethod(METHOD),
exactly(1)
)
.respond(
response()
.withStatusCode(HttpStatus.SC_OK)
.withBody("{\"status\":\"ok\"}")
);
}
private static int getFreePort () throws IOException {
try (ServerSocket serverSocket = new ServerSocket(0)) {
return serverSocket.getLocalPort();
}
}
}

View File

@ -31,7 +31,8 @@ import org.apache.http.protocol.HttpContext;
import org.apache.http.ssl.SSLContexts;
import org.junit.jupiter.api.Test;
class HttpAsyncClientV4LiveTest {
class HttpAsyncClientV4LiveTest extends GetRequestMockServer {
private static final String HOST = "http://www.google.com";
private static final String HOST_WITH_SSL = "https://mms.nw.ru/";
@ -87,7 +88,7 @@ class HttpAsyncClientV4LiveTest {
void whenUseProxyWithHttpClient_thenCorrect() throws Exception {
final CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
client.start();
final HttpHost proxy = new HttpHost("127.0.0.1", 8080);
final HttpHost proxy = new HttpHost("127.0.0.1", GetRequestMockServer.serverPort);
final RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
final HttpGet request = new HttpGet(HOST_WITH_PROXY);
request.setConfig(config);

View File

@ -9,3 +9,5 @@ You can build the project from the command line using: *mvn clean install*, or i
- [Guide to Check if Apache Kafka Server Is Running](https://www.baeldung.com/apache-kafka-check-server-is-running)
- [Add Custom Headers to a Kafka Message](https://www.baeldung.com/java-kafka-custom-headers)
- [Get Last N Messages in Apache Kafka Topic](https://www.baeldung.com/java-apache-kafka-get-last-n-messages)
- [Is a Key Required as Part of Sending Messages to Kafka?](https://www.baeldung.com/java-kafka-message-key)
- [Read Data From the Beginning Using Kafka Consumer API](https://www.baeldung.com/java-kafka-consumer-api-read)

View File

@ -12,4 +12,5 @@ This module contains articles about Apache POI.
- [Finding the Last Row in an Excel Spreadsheet From Java](https://www.baeldung.com/java-excel-find-last-row)
- [Setting Formulas in Excel with Apache POI](https://www.baeldung.com/java-apache-poi-set-formulas)
- [Set the Date Format Using Apache POI](https://www.baeldung.com/java-apache-poi-date-format)
- [Replacing Variables in a Document Template with Java](https://www.baeldung.com/java-replace-pattern-word-document-doc-docx)
- More articles: [[<-- prev]](../apache-poi)

View File

@ -1,7 +1,7 @@
<?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">
<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>
<artifactId>apache-poi-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
@ -19,10 +19,15 @@
<artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>${poi.version}</version>
</dependency>
</dependencies>
<properties>
<poi.version>5.2.0</poi.version>
<poi.version>5.2.3</poi.version>
</properties>
</project>

View File

@ -0,0 +1,38 @@
package com.baeldung.poi.replacevariables;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
public class DocTextReplacer {
public void replaceText() throws IOException {
String filePath = getClass().getClassLoader()
.getResource("baeldung.doc")
.getPath();
try (InputStream inputStream = new FileInputStream(filePath); POIFSFileSystem fileSystem = new POIFSFileSystem(inputStream)) {
HWPFDocument doc = new HWPFDocument(fileSystem);
doc = replaceText(doc, "Baeldung", "Hello");
saveFile(filePath, doc);
doc.close();
}
}
private HWPFDocument replaceText(HWPFDocument doc, String originalText, String updatedText) {
Range range = doc.getRange();
range.replaceText(originalText, updatedText);
return doc;
}
private void saveFile(String filePath, HWPFDocument doc) throws IOException {
try (FileOutputStream out = new FileOutputStream(filePath)) {
doc.write(out);
}
}
}

View File

@ -0,0 +1,63 @@
package com.baeldung.poi.replacevariables;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
public class DocxNaiveTextReplacer {
public void replaceText() throws IOException {
String filePath = getClass().getClassLoader()
.getResource("baeldung-copy.docx")
.getPath();
try (InputStream inputStream = new FileInputStream(filePath)) {
XWPFDocument doc = new XWPFDocument(inputStream);
doc = replaceText(doc, "Baeldung", "Hello");
saveFile(filePath, doc);
doc.close();
}
}
private XWPFDocument replaceText(XWPFDocument doc, String originalText, String updatedText) {
replaceTextInParagraphs(doc.getParagraphs(), originalText, updatedText);
for (XWPFTable tbl : doc.getTables()) {
for (XWPFTableRow row : tbl.getRows()) {
for (XWPFTableCell cell : row.getTableCells()) {
replaceTextInParagraphs(cell.getParagraphs(), originalText, updatedText);
}
}
}
return doc;
}
private void replaceTextInParagraphs(List<XWPFParagraph> paragraphs, String originalText, String updatedText) {
paragraphs.forEach(paragraph -> replaceTextInParagraph(paragraph, originalText, updatedText));
}
private void replaceTextInParagraph(XWPFParagraph paragraph, String originalText, String updatedText) {
List<XWPFRun> runs = paragraph.getRuns();
for (XWPFRun run : runs) {
String text = run.getText(0);
if (text != null && text.contains(originalText)) {
String updatedRunText = text.replace(originalText, updatedText);
run.setText(updatedRunText, 0);
}
}
}
private void saveFile(String filePath, XWPFDocument doc) throws IOException {
try (FileOutputStream out = new FileOutputStream(filePath)) {
doc.write(out);
}
}
}

View File

@ -0,0 +1,65 @@
package com.baeldung.poi.replacevariables;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Objects;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
public class DocxTextReplacer {
public void replaceText() throws IOException {
String filePath = getClass().getClassLoader()
.getResource("baeldung.docx")
.getPath();
try (InputStream inputStream = new FileInputStream(filePath)) {
XWPFDocument doc = new XWPFDocument(inputStream);
doc = replaceText(doc, "Baeldung", "Hello");
saveFile(filePath, doc);
doc.close();
}
}
private XWPFDocument replaceText(XWPFDocument doc, String originalText, String updatedText) {
replaceTextInParagraphs(doc.getParagraphs(), originalText, updatedText);
for (XWPFTable tbl : doc.getTables()) {
for (XWPFTableRow row : tbl.getRows()) {
for (XWPFTableCell cell : row.getTableCells()) {
replaceTextInParagraphs(cell.getParagraphs(), originalText, updatedText);
}
}
}
return doc;
}
private void replaceTextInParagraphs(List<XWPFParagraph> paragraphs, String originalText, String updatedText) {
paragraphs.forEach(paragraph -> replaceTextInParagraph(paragraph, originalText, updatedText));
}
private void replaceTextInParagraph(XWPFParagraph paragraph, String originalText, String updatedText) {
String paragraphText = paragraph.getParagraphText();
if (paragraphText.contains(originalText)) {
String updatedParagraphText = paragraphText.replace(originalText, updatedText);
while (paragraph.getRuns().size() > 0) {
paragraph.removeRun(0);
}
XWPFRun newRun = paragraph.createRun();
newRun.setText(updatedParagraphText);
}
}
private void saveFile(String filePath, XWPFDocument doc) throws IOException {
try (FileOutputStream out = new FileOutputStream(filePath)) {
doc.write(out);
}
}
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,31 @@
package com.baeldung.poi.replacevariables;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.junit.jupiter.api.Test;
class DocTextReplacerUnitTest {
@Test
void whenReplaceText_ThenTextReplaced() throws IOException {
new DocTextReplacer().replaceText();
String filePath = getClass().getClassLoader()
.getResource("baeldung.doc")
.getPath();
try (FileInputStream fis = new FileInputStream(filePath); HWPFDocument document = new HWPFDocument(fis); WordExtractor extractor = new WordExtractor(document)) {
long occurrencesOfHello = Arrays.stream(extractor.getText()
.split("\\s+"))
.filter(s -> s.contains("Hello"))
.count();
assertEquals(5, occurrencesOfHello);
}
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.poi.replacevariables;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.junit.jupiter.api.Test;
class DocxNaiveTextReplacerUnitTest {
@Test
void whenReplaceText_ThenTextReplaced() throws IOException {
new DocxNaiveTextReplacer().replaceText();
String filePath = getClass().getClassLoader()
.getResource("baeldung-copy.docx")
.getPath();
try (FileInputStream fis = new FileInputStream(filePath); XWPFDocument document = new XWPFDocument(fis); XWPFWordExtractor extractor = new XWPFWordExtractor(document)) {
long occurrencesOfHello = Arrays.stream(extractor.getText()
.split("\\s+"))
.filter(s -> s.contains("Hello"))
.count();
assertTrue(occurrencesOfHello < 5);
}
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.poi.replacevariables;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.junit.jupiter.api.Test;
class DocxTestReplacerUnitTest {
@Test
void whenReplaceText_ThenTextReplaced() throws IOException {
new DocxTextReplacer().replaceText();
String filePath = getClass().getClassLoader()
.getResource("baeldung.docx")
.getPath();
try (FileInputStream fis = new FileInputStream(filePath); XWPFDocument document = new XWPFDocument(fis); XWPFWordExtractor extractor = new XWPFWordExtractor(document)) {
long occurrencesOfHello = Arrays.stream(extractor.getText()
.split("\\s+"))
.filter(s -> s.contains("Hello"))
.count();
assertEquals(5, occurrencesOfHello);
}
}
}

View File

@ -21,4 +21,4 @@ Two scripts are included to easily start middleware using Docker matching the pr
- [Snapshotting Aggregates in Axon](https://www.baeldung.com/axon-snapshotting-aggregates)
- [Dispatching Queries in Axon Framework](https://www.baeldung.com/axon-query-dispatching)
- [Persisting the Query Model](https://www.baeldung.com/axon-persisting-query-model)
- [Using and Testing Axon Applications via REST](https://www.baeldung.com/using-and-testing-axon-applications-via-rest)
- [Using and Testing Axon Applications via REST](https://www.baeldung.com/axon-using-and-testing-rest)

View File

@ -19,24 +19,13 @@
<dependency>
<groupId>org.checkerframework</groupId>
<artifactId>checker-qual</artifactId>
<version>${checker-qual.version}</version>
<version>${checker.version}</version>
</dependency>
<dependency>
<groupId>org.checkerframework</groupId>
<artifactId>checker</artifactId>
<version>${checker.version}</version>
</dependency>
<dependency>
<groupId>org.checkerframework</groupId>
<artifactId>jdk8</artifactId>
<version>${jdk8.version}</version>
</dependency>
<!-- The Type Annotations compiler. Uncomment if using annotations in comments. -->
<dependency>
<groupId>org.checkerframework</groupId>
<artifactId>compiler</artifactId>
<version>${checkerframework.compiler.version}</version>
</dependency>
</dependencies>
<build>
@ -45,32 +34,34 @@
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<!-- Uncomment the following line to use the type annotations compiler. -->
<!-- <fork>true</fork> -->
<compilerArguments>
<Xmaxerrs>10000</Xmaxerrs>
<Xmaxwarns>10000</Xmaxwarns>
</compilerArguments>
<fork>true</fork>
<compilerArgument>-Xlint:all</compilerArgument>
<showWarnings>true</showWarnings>
<annotationProcessorPaths>
<path>
<groupId>org.checkerframework</groupId>
<artifactId>checker</artifactId>
<version>${checker.version}</version>
</path>
</annotationProcessorPaths>
<annotationProcessors>
<!-- Add all the checkers you want to enable here -->
<annotationProcessor>org.checkerframework.checker.nullness.NullnessChecker</annotationProcessor>
<annotationProcessor>org.checkerframework.checker.interning.InterningChecker</annotationProcessor>
<annotationProcessor>org.checkerframework.checker.fenum.FenumChecker</annotationProcessor>
<annotationProcessor>org.checkerframework.checker.formatter.FormatterChecker</annotationProcessor>
<annotationProcessor>org.checkerframework.checker.regex.RegexChecker</annotationProcessor>
</annotationProcessors>
<compilerArgs>
<arg>-AprintErrorStack</arg>
<!-- location of the annotated JDK, which comes from a Maven dependency -->
<arg>-Xbootclasspath/p:${annotatedJdk}</arg>
<!-- -->
<!-- Uncomment the following line to use the type annotations compiler. -->
<!-- <arg>-J-Xbootclasspath/p:${typeAnnotationsJavac}</arg> -->
<!-- Uncomment the following line to turn type-checking warnings into errors. -->
<compilerArgs combine.children="append">
<arg>-Awarns</arg>
<arg>-J--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED</arg>
<arg>-J--add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED</arg>
<arg>-J--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED</arg>
<arg>-J--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED</arg>
<arg>-J--add-exports=jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED</arg>
<arg>-J--add-exports=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED</arg>
<arg>-J--add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED</arg>
<arg>-J--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED</arg>
<arg>-J--add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED</arg>
</compilerArgs>
</configuration>
</plugin>
@ -78,14 +69,7 @@
</build>
<properties>
<!-- These properties will be set by the Maven Dependency plugin -->
<annotatedJdk>${org.checkerframework:jdk8:jar}</annotatedJdk>
<!-- Uncomment to use the Type Annotations compiler. -->
<!-- <typeAnnotationsJavac>${org.checkerframework:compiler:jar}</typeAnnotationsJavac> -->
<checker-qual.version>2.3.1</checker-qual.version>
<checker.version>2.3.1</checker.version>
<jdk8.version>2.3.1</jdk8.version>
<checkerframework.compiler.version>2.3.1</checkerframework.compiler.version>
<checker.version>3.35.0</checker.version>
</properties>
</project>

View File

@ -0,0 +1,21 @@
package com.baeldung.daysinmonth;
import java.time.YearMonth;
import java.util.Calendar;
public class DaysInMonthUtils {
public int getDaysInMonthWithYearOfMonth(int month, int year) {
YearMonth yearMonth = YearMonth.of(year, month);
return yearMonth.lengthOfMonth();
}
public int getDaysInMonthWithCalendar(int month, int year) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month - 1);
return calendar.getActualMaximum(Calendar.DATE);
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.daysinmonth;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class DaysInMonthUtilsUnitTest {
@Test
void whenGetDaysInMonthWithYearOfMonth_thenCorrectResult() {
assertEquals(31, new DaysInMonthUtils().getDaysInMonthWithYearOfMonth(3, 2024));
assertEquals(30, new DaysInMonthUtils().getDaysInMonthWithYearOfMonth(11, 1999));
assertEquals(28, new DaysInMonthUtils().getDaysInMonthWithYearOfMonth(2, 2025));
assertEquals(29, new DaysInMonthUtils().getDaysInMonthWithYearOfMonth(2, 2004));
}
@Test
void whenGetDaysInMonthWithCalendar_thenCorrectResult() {
assertEquals(31, new DaysInMonthUtils().getDaysInMonthWithCalendar(3, 2024));
assertEquals(30, new DaysInMonthUtils().getDaysInMonthWithCalendar(11, 1999));
assertEquals(28, new DaysInMonthUtils().getDaysInMonthWithCalendar(2, 2025));
assertEquals(29, new DaysInMonthUtils().getDaysInMonthWithCalendar(2, 2004));
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung.spliteratorAPI;
package com.baeldung.spliterator;
import java.util.List;

View File

@ -1,4 +1,4 @@
package com.baeldung.spliteratorAPI;
package com.baeldung.spliterator;
public class Author {
private String name;

View File

@ -1,7 +1,5 @@
package com.baeldung.spliteratorAPI;
package com.baeldung.spliterator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Executor {
@ -11,9 +9,4 @@ public class Executor {
RelatedAuthorCounter::accumulate, RelatedAuthorCounter::combine);
return wordCounter.getCounter();
}
public static List<Article> generateElements() {
return Stream.generate(() -> new Article("Java")).limit(35000).collect(Collectors.toList());
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung.spliteratorAPI;
package com.baeldung.spliterator;
public class RelatedAuthorCounter {
private final int counter;

View File

@ -1,4 +1,4 @@
package com.baeldung.spliteratorAPI;
package com.baeldung.spliterator;
import java.util.List;
import java.util.Spliterator;

View File

@ -1,27 +0,0 @@
package com.baeldung.spliteratorAPI;
import java.util.Spliterator;
import java.util.concurrent.Callable;
public class Task implements Callable<String> {
private Spliterator<Article> spliterator;
private final static String SUFFIX = "- published by Baeldung";
public Task(Spliterator<Article> spliterator) {
this.spliterator = spliterator;
}
@Override
public String call() {
int current = 0;
while (spliterator.tryAdvance(article -> {
article.setName(article.getName()
.concat(SUFFIX));
})) {
current++;
}
;
return Thread.currentThread()
.getName() + ":" + current;
}
}

View File

@ -0,0 +1,76 @@
package com.baeldung.spliterator;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Spliterator;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import org.junit.Before;
import org.junit.Test;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class ExecutorUnitTest {
Article article;
Stream<Author> stream;
Spliterator<Author> spliterator;
@Before
public void init() {
article = new Article(Arrays.asList(new Author("Ahmad", 0), new Author("Eugen", 0), new Author("Alice", 1), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0),
new Author("Alice", 1), new Author("Mike", 0), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1),
new Author("Mike", 0), new Author("Michał", 0), new Author("Loredana", 1)), 0);
spliterator = new RelatedAuthorSpliterator(article.getListOfAuthors());
}
@Test
public void givenAstreamOfAuthors_whenProcessedInParallelWithCustomSpliterator_coubtProducessRightOutput() {
Stream<Author> stream2 = StreamSupport.stream(spliterator, true);
assertThat(Executor.countAutors(stream2.parallel())).isEqualTo(9);
}
@Test
public void givenAStreamOfArticles_whenProcessedSequentiallyWithSpliterator_ProducessRightOutput() {
List<Article> articles = Stream.generate(() -> new Article("Java"))
.limit(35000)
.collect(Collectors.toList());
Spliterator<Article> spliterator = articles.spliterator();
while (spliterator.tryAdvance(article -> article.setName(article.getName()
.concat("- published by Baeldung"))))
;
articles.forEach(article -> assertThat(article.getName()).isEqualTo("Java- published by Baeldung"));
}
@Test
public void givenAStreamOfArticle_whenProcessedUsingTrySplit_thenSplitIntoEqualHalf() {
List<Article> articles = Stream.generate(() -> new Article("Java"))
.limit(35000)
.collect(Collectors.toList());
Spliterator<Article> split1 = articles.spliterator();
Spliterator<Article> split2 = split1.trySplit();
log.info("Size: " + split1.estimateSize());
log.info("Characteristics: " + split1.characteristics());
List<Article> articlesListOne = new ArrayList<>();
List<Article> articlesListTwo = new ArrayList<>();
split1.forEachRemaining(articlesListOne::add);
split2.forEachRemaining(articlesListTwo::add);
assertThat(articlesListOne.size()).isEqualTo(17500);
assertThat(articlesListTwo.size()).isEqualTo(17500);
assertThat(articlesListOne).doesNotContainAnyElementsOf(articlesListTwo);
}
}

View File

@ -1,44 +0,0 @@
package com.baeldung.spliteratorAPI;
import java.util.Arrays;
import java.util.Spliterator;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import static org.assertj.core.api.Assertions.*;
import org.junit.Before;
import org.junit.Test;
public class ExecutorUnitTest {
Article article;
Stream<Author> stream;
Spliterator<Author> spliterator;
Spliterator<Article> split1;
Spliterator<Article> split2;
@Before
public void init() {
article = new Article(Arrays.asList(new Author("Ahmad", 0), new Author("Eugen", 0), new Author("Alice", 1),
new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0),
new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0),
new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1),
new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1),
new Author("Mike", 0), new Author("Michał", 0), new Author("Loredana", 1)), 0);
stream = article.getListOfAuthors().stream();
split1 = Executor.generateElements().spliterator();
split2 = split1.trySplit();
spliterator = new RelatedAuthorSpliterator(article.getListOfAuthors());
}
@Test
public void givenAstreamOfAuthors_whenProcessedInParallelWithCustomSpliterator_coubtProducessRightOutput() {
Stream<Author> stream2 = StreamSupport.stream(spliterator, true);
assertThat(Executor.countAutors(stream2.parallel())).isEqualTo(9);
}
@Test
public void givenSpliterator_whenAppliedToAListOfArticle_thenSplittedInHalf() {
assertThat(new Task(split1).call()).containsSequence(Executor.generateElements().size() / 2 + "");
assertThat(new Task(split2).call()).containsSequence(Executor.generateElements().size() / 2 + "");
}
}

View File

@ -5,7 +5,7 @@ This module contains complete guides about arrays in Java
### Relevant Articles:
- [Arrays in Java: A Reference Guide](https://www.baeldung.com/java-arrays-guide)
- [Guide to the java.util.Arrays Class](https://www.baeldung.com/java-util-arrays)
- [What is [Ljava.lang.Object;?](https://www.baeldung.com/java-tostring-array)
- [What Is [Ljava.lang.Object;?](https://www.baeldung.com/java-tostring-array)
- [Guide to ArrayStoreException](https://www.baeldung.com/java-arraystoreexception)
- [Creating a Generic Array in Java](https://www.baeldung.com/java-generic-array)
- [Maximum Size of Java Arrays](https://www.baeldung.com/java-arrays-max-size)

View File

@ -3,5 +3,5 @@
This module contains articles about multidimensional arrays in Java
### Relevant Articles:
- [Multi-Dimensional Arrays In Java](https://www.baeldung.com/java-jagged-arrays)
- [Looping Diagonally Through a 2d Java Array](https://www.baeldung.com/java-loop-diagonal-array)
- [Multi-Dimensional Arrays in Java](https://www.baeldung.com/java-jagged-arrays)
- [Looping Diagonally Through a 2d Java Array](https://www.baeldung.com/java-loop-diagonal-array)

View File

@ -7,7 +7,7 @@ This module contains articles about advanced operations on arrays in Java. They
- [How to Copy an Array in Java](https://www.baeldung.com/java-array-copy)
- [Arrays.deepEquals](https://www.baeldung.com/java-arrays-deepequals)
- [Find Sum and Average in a Java Array](https://www.baeldung.com/java-array-sum-average)
- [Intersection Between two Integer Arrays](https://www.baeldung.com/java-array-intersection)
- [Intersection Between Two Integer Arrays](https://www.baeldung.com/java-array-intersection)
- [Comparing Arrays in Java](https://www.baeldung.com/java-comparing-arrays)
- [Concatenate Two Arrays in Java](https://www.baeldung.com/java-concatenate-arrays)
- [Performance of System.arraycopy() vs. Arrays.copyOf()](https://www.baeldung.com/java-system-arraycopy-arrays-copyof-performance)

View File

@ -0,0 +1,49 @@
package com.baeldung.arrayconcat;
import com.google.common.primitives.Bytes;
import org.apache.commons.lang3.ArrayUtils;
import java.nio.ByteBuffer;
public class CombiningByteArrays {
public byte[] combineArraysUsingArrayCopy(byte[] first, byte[] second) {
byte[] combined = new byte[first.length + second.length];
System.arraycopy(first, 0, combined, 0, first.length);
System.arraycopy(second, 0, combined, first.length, second.length);
return combined;
}
public byte[] combineArraysUsingByteBuffer(byte[] first, byte[] second, byte[] third) {
byte[] combined = new byte[first.length + second.length + third.length];
ByteBuffer buffer = ByteBuffer.wrap(combined);
buffer.put(first);
buffer.put(second);
buffer.put(third);
return buffer.array();
}
public byte[] combineArraysUsingCustomMethod(byte[] first, byte[] second) {
byte[] combined = new byte[first.length + second.length];
for (int i = 0; i < combined.length; ++i) {
combined[i] = i < first.length ? first[i] : second[i - first.length];
}
return combined;
}
public byte[] combineArraysUsingGuava(byte[] first, byte[] second, byte[] third) {
byte[] combined = Bytes.concat(first, second, third);
return combined;
}
public byte[] combineArraysUsingApacheCommons(byte[] first, byte[] second) {
byte[] combined = ArrayUtils.addAll(first, second);
return combined;
}
}

View File

@ -0,0 +1,73 @@
package com.baeldung.arrayconcat;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
public class CombiningByteArraysUnitTest {
CombiningByteArrays combiningByteArrays;
@Before
public void init() {
combiningByteArrays = new CombiningByteArrays();
}
@Test
public void givenTwoArrays_whenCombinedUsingArraysCopy_thenArrayContainingAllElementsMustBeReturned() {
byte[] first = {69, 121, 101, 45, 62, 118, 114};
byte[] second = {58, 120, 100, 46, 64, 114, 103, 117};
byte[] combined = combiningByteArrays.combineArraysUsingArrayCopy(first, second);
byte[] expectedArray = {69, 121, 101, 45, 62, 118, 114, 58, 120, 100, 46, 64, 114, 103, 117};
assertArrayEquals(expectedArray, combined);
}
@Test
public void givenTwoArrays_whenCombinedUsingByteBuffer_thenArrayContainingAllElementsMustBeReturned() {
byte[] first = {69, 121, 101, 45};
byte[] second = {64, 114, 103, 117};
byte[] third = {11, 22, 33};
byte[] combined = combiningByteArrays.combineArraysUsingByteBuffer(first, second, third);
byte[] expectedArray = {69, 121, 101, 45, 64, 114, 103, 117, 11, 22, 33};
assertArrayEquals(expectedArray, combined);
}
@Test
public void givenTwoArrays_whenCombinedUsingCustomMethod_thenArrayContainingAllElementsMustBeReturned() {
byte[] first = {101, 45, 62 };
byte[] second = {58, 120, 100, 46, 64, 114};
byte[] combined = combiningByteArrays.combineArraysUsingCustomMethod(first, second);
byte[] expectedArray = {101, 45, 62, 58, 120, 100, 46, 64, 114};
assertArrayEquals(expectedArray, combined);
}
@Test
public void givenTwoArrays_whenCombinedUsingGuava_thenArrayContainingAllElementsMustBeReturned() {
byte[] first = {69, 121, 101, 118, 114};
byte[] second = {58, 120, 114, 103, 117};
byte[] third = {11, 22, 33};
byte[] combined = combiningByteArrays.combineArraysUsingGuava(first, second, third);
byte[] expectedArray = {69, 121, 101, 118, 114, 58, 120, 114, 103, 117, 11, 22, 33};
assertArrayEquals(expectedArray, combined);
}
@Test
public void givenTwoArrays_whenCombinedUsingApacheCommons_thenArrayContainingAllElementsMustBeReturned() {
byte[] first = {45, 62, 114};
byte[] second = {58, 120, 100};
byte[] combined = combiningByteArrays.combineArraysUsingApacheCommons(first, second);
byte[] expectedArray = {45, 62, 114, 58, 120, 100};
assertArrayEquals(expectedArray, combined);
}
}

View File

@ -8,7 +8,7 @@
- [Join and Split Arrays and Collections in Java](https://www.baeldung.com/java-join-and-split)
- [Java Combine Multiple Collections](https://www.baeldung.com/java-combine-multiple-collections)
- [Combining Different Types of Collections in Java](https://www.baeldung.com/java-combine-collections)
- [Shuffling Collections In Java](https://www.baeldung.com/java-shuffle-collection)
- [Shuffling Collections in Java](https://www.baeldung.com/java-shuffle-collection)
- [Sorting in Java](https://www.baeldung.com/java-sorting)
- [Getting the Size of an Iterable in Java](https://www.baeldung.com/java-iterable-size)
- [Java Null-Safe Streams from Collections](https://www.baeldung.com/java-null-safe-streams-from-collections)

View File

@ -3,7 +3,7 @@
This module contains articles about conversions among Collection types and arrays in Java.
### Relevant Articles:
- [Converting between an Array and a List in Java](https://www.baeldung.com/convert-array-to-list-and-list-to-array)
- [Converting Between an Array and a List in Java](https://www.baeldung.com/convert-array-to-list-and-list-to-array)
- [Converting Between an Array and a Set in Java](https://www.baeldung.com/convert-array-to-set-and-set-to-array)
- [Convert a Map to an Array, List or Set in Java](https://www.baeldung.com/convert-map-values-to-array-list-set)
- [Converting a List to String in Java](https://www.baeldung.com/java-list-to-string)

View File

@ -3,8 +3,8 @@
This module contains articles about the Java List collection
### Relevant Articles:
- [Check If Two Lists are Equal in Java](https://www.baeldung.com/java-test-a-list-for-ordinality-and-equality)
- [Java 8 Streams: Find Items From One List Based On Values From Another List](https://www.baeldung.com/java-streams-find-list-items)
- [Check if Two Lists Are Equal in Java](https://www.baeldung.com/java-test-a-list-for-ordinality-and-equality)
- [Java 8 Streams: Find Items From One List Based on Values From Another List](https://www.baeldung.com/java-streams-find-list-items)
- [A Guide to the Java LinkedList](https://www.baeldung.com/java-linkedlist)
- [Java List UnsupportedOperationException](https://www.baeldung.com/java-list-unsupported-operation-exception)
- [Java List Initialization in One Line](https://www.baeldung.com/java-init-list-one-line)

View File

@ -7,3 +7,6 @@ This module contains articles about the Java List collection
- [Finding All Duplicates in a List in Java](https://www.baeldung.com/java-list-find-duplicates)
- [Moving Items Around in an Arraylist](https://www.baeldung.com/java-arraylist-move-items)
- [Check if a List Contains an Element From Another List in Java](https://www.baeldung.com/java-check-elements-between-lists)
- [Array vs. List Performance in Java](https://www.baeldung.com/java-array-vs-list-performance)
- [Set Default Value for Elements in List](https://www.baeldung.com/java-list-set-default-values)
- [Get Unique Values From an ArrayList In Java](https://www.baeldung.com/java-unique-values-arraylist)

View File

@ -0,0 +1,41 @@
package com.baeldung.java.uniqueelements;
import static java.util.stream.Collectors.toList;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import org.junit.jupiter.api.Test;
public class UniqueElementsInListUnitTest {
// @formatter:off
private static final List<String> MY_LIST = Arrays.asList(new String[]{
"Microsoft Windows",
"Mac OS",
"GNU Linux",
"Free BSD",
"GNU Linux",
"Mac OS"});
// @formatter:on
@Test
void whenConvertToSet_thenGetExpectedResult() {
List<String> result = new ArrayList<>(new HashSet<>(MY_LIST));
assertThat(result).containsExactlyInAnyOrder("Free BSD", "Microsoft Windows", "Mac OS", "GNU Linux");
result = new ArrayList<>(new LinkedHashSet<>(MY_LIST));
assertThat(result).containsExactly("Microsoft Windows", "Mac OS", "GNU Linux", "Free BSD");
}
@Test
void whenUsingStream_thenGetExpectedResult() {
List<String> result = MY_LIST.stream()
.distinct()
.collect(toList());
assertThat(result).containsExactly("Microsoft Windows", "Mac OS", "GNU Linux", "Free BSD");
}
}

View File

@ -4,8 +4,8 @@ This module contains articles about the Java List collection
### Relevant Articles:
- [Java Get Random Item/Element From a List](http://www.baeldung.com/java-random-list-element)
- [Removing all Nulls from a List in Java](http://www.baeldung.com/java-remove-nulls-from-list)
- [Removing all duplicates from a List in Java](http://www.baeldung.com/java-remove-duplicates-from-list)
- [Removing All Nulls From a List in Java](https://www.baeldung.com/java-remove-nulls-from-list)
- [Removing All Duplicates From a List in Java](https://www.baeldung.com/java-remove-duplicates-from-list)
- [How to TDD a List Implementation in Java](http://www.baeldung.com/java-test-driven-list)
- [Iterating Backward Through a List](http://www.baeldung.com/java-list-iterate-backwards)
- [Remove the First Element from a List](http://www.baeldung.com/java-remove-first-element-from-list)

View File

@ -8,7 +8,7 @@ This module contains articles about Map data structures in Java.
- [A Guide to Java HashMap](https://www.baeldung.com/java-hashmap)
- [Guide to WeakHashMap in Java](https://www.baeldung.com/java-weakhashmap)
- [Map to String Conversion in Java](https://www.baeldung.com/java-map-to-string-conversion)
- [Iterate over a Map in Java](https://www.baeldung.com/java-iterate-map)
- [Iterate Over a Map in Java](https://www.baeldung.com/java-iterate-map)
- [Merging Two Maps with Java 8](https://www.baeldung.com/java-merge-maps)
- [Sort a HashMap in Java](https://www.baeldung.com/java-hashmap-sort)
- [Finding the Highest Value in a Java Map](https://www.baeldung.com/java-find-map-max)

View File

@ -1,2 +1,5 @@
## Relevant Articles
- [Copying All Keys and Values From One Hashmap Onto Another Without Replacing Existing Keys and Values](https://www.baeldung.com/java-copy-hashmap-no-changes)
- [Convert Hashmap to JSON Object in Java](https://www.baeldung.com/java-convert-hashmap-to-json-object)
- [Converting Map<String, Object> to Map<String, String> in Java](https://www.baeldung.com/java-converting-map-string-object-to-string-string)
- [Converting Object To Map in Java](https://www.baeldung.com/java-convert-object-to-map)

View File

@ -0,0 +1,92 @@
package com.baeldung.map.generictypeconversion;
import static java.util.stream.Collectors.toMap;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
import com.google.common.collect.Maps;
public class ConvertMapWithTypeParamUnitTest {
private static final Map<String, Object> MAP1 = Maps.newHashMap();
static {
MAP1.put("K01", "GNU Linux");
MAP1.put("K02", "Mac OS");
MAP1.put("K03", "MS Windows");
}
private static final Map<String, String> EXPECTED_MAP1 = Maps.newHashMap();
static {
EXPECTED_MAP1.put("K01", "GNU Linux");
EXPECTED_MAP1.put("K02", "Mac OS");
EXPECTED_MAP1.put("K03", "MS Windows");
}
private static final Map<String, Object> MAP2 = Maps.newHashMap();
static {
MAP2.put("K01", "GNU Linux");
MAP2.put("K02", "Mac OS");
MAP2.put("K03", BigDecimal.ONE);
}
private static final Map<String, String> EXPECTED_MAP2_STRING_VALUES = Maps.newHashMap();
static {
EXPECTED_MAP2_STRING_VALUES.put("K01", "GNU Linux");
EXPECTED_MAP2_STRING_VALUES.put("K02", "Mac OS");
EXPECTED_MAP2_STRING_VALUES.put("K03", "1");
}
@Test
void whenCastingToMap_shouldGetExpectedResult() {
Map<String, String> result = (Map) MAP1;
assertEquals(EXPECTED_MAP1, result);
Map<String, String> result2 = (Map) MAP2;
assertFalse(result2.get("K03") instanceof String);
}
Map<String, String> checkAndTransform(Map<String, Object> inputMap) {
Map<String, String> result = new HashMap<>();
for (Map.Entry<String, Object> entry : inputMap.entrySet()) {
try {
result.put(entry.getKey(), (String) entry.getValue());
} catch (ClassCastException e) {
throw e;
}
}
return result;
}
@Test
void whenCheckAndTransform_shouldGetExpectedResult() {
Map<String, String> result = checkAndTransform(MAP1);
assertEquals(EXPECTED_MAP1, result);
assertThrows(ClassCastException.class, () -> checkAndTransform(MAP2));
}
@Test
void whenUsingStringValueOf_shouldGetExpectedResult() {
Map<String, String> result = MAP1.entrySet()
.stream()
.collect(toMap(Map.Entry::getKey, e -> String.valueOf(e.getValue())));
assertEquals(EXPECTED_MAP1, result);
Map<String, String> result2 = MAP2.entrySet()
.stream()
.collect(toMap(Map.Entry::getKey, e -> String.valueOf(e.getValue())));
assertEquals(EXPECTED_MAP2_STRING_VALUES, result2);
}
}

View File

@ -15,5 +15,5 @@ This module contains articles about advanced topics about multithreading with co
- [The ABA Problem in Concurrency](https://www.baeldung.com/cs/aba-concurrency)
- [Introduction to Lock-Free Data Structures with Java Examples](https://www.baeldung.com/lock-free-programming)
- [Introduction to Exchanger in Java](https://www.baeldung.com/java-exchanger)
- [Why Not To Start A Thread In The Constructor?](https://www.baeldung.com/java-thread-constructor)
- [Why Not to Start a Thread in the Constructor?](https://www.baeldung.com/java-thread-constructor)
- [[<-- previous]](/core-java-modules/core-java-concurrency-advanced-2)

View File

@ -7,7 +7,7 @@ This module contains articles about basic Java concurrency
- [How to Delay Code Execution in Java](https://www.baeldung.com/java-delay-code-execution)
- [Difference Between Wait and Sleep in Java](https://www.baeldung.com/java-wait-and-sleep)
- [Guide to AtomicMarkableReference](https://www.baeldung.com/java-atomicmarkablereference)
- [Why are Local Variables Thread-Safe in Java](https://www.baeldung.com/java-local-variables-thread-safe)
- [Why Are Local Variables Thread-Safe in Java](https://www.baeldung.com/java-local-variables-thread-safe)
- [How to Stop Execution After a Certain Time in Java](https://www.baeldung.com/java-stop-execution-after-certain-time)
- [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)

View File

@ -7,4 +7,5 @@ This module contains articles about basic Java concurrency.
- [How to Handle InterruptedException in Java](https://www.baeldung.com/java-interrupted-exception)
- [Thread.sleep() vs Awaitility.await()](https://www.baeldung.com/java-thread-sleep-vs-awaitility-await)
- [Is CompletableFuture Non-blocking?](https://www.baeldung.com/java-completablefuture-non-blocking)
- [Returning a Value After Finishing Threads Job in Java](https://www.baeldung.com/java-return-value-after-thread-finish)
- [[<-- Prev]](../core-java-concurrency-basic-2)

View File

@ -0,0 +1,29 @@
package com.baeldung.concurrent.threadreturnvalue.task;
import java.math.BigInteger;
public class FactorialCalculator {
public static BigInteger factorial(BigInteger end) {
BigInteger start = BigInteger.ONE;
BigInteger res = BigInteger.ONE;
for (int i = start.add(BigInteger.ONE)
.intValue(); i <= end.intValue(); i++) {
res = res.multiply(BigInteger.valueOf(i));
}
return res;
}
public static BigInteger factorial(BigInteger start, BigInteger end) {
BigInteger res = start;
for (int i = start.add(BigInteger.ONE)
.intValue(); i <= end.intValue(); i++) {
res = res.multiply(BigInteger.valueOf(i));
}
return res;
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.concurrent.threadreturnvalue.task.callable;
import java.math.BigInteger;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class CallableExecutor {
public BigInteger execute(List<CallableFactorialTask> tasks) {
BigInteger result = BigInteger.ZERO;
ExecutorService cachedPool = Executors.newCachedThreadPool();
List<Future<BigInteger>> futures;
try {
futures = cachedPool.invokeAll(tasks);
} catch (InterruptedException e) {
// exception handling example
throw new RuntimeException(e);
}
for (Future<BigInteger> future : futures) {
try {
result = result.add(future.get());
} catch (InterruptedException | ExecutionException e) {
// exception handling example
throw new RuntimeException(e);
}
}
return result;
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.concurrent.threadreturnvalue.task.callable;
import static com.baeldung.concurrent.threadreturnvalue.task.FactorialCalculator.factorial;
import java.math.BigInteger;
import java.util.concurrent.Callable;
public class CallableFactorialTask implements Callable<BigInteger> {
private final Integer value;
public CallableFactorialTask(int value) {
this.value = value;
}
@Override
public BigInteger call() {
return factorial(BigInteger.valueOf(value));
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.concurrent.threadreturnvalue.task.fork;
import java.math.BigInteger;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
public class ForkExecutor {
private final ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();
public BigInteger execute(ForkFactorialTask forkFactorial) {
return forkJoinPool.invoke(forkFactorial);
}
public BigInteger execute(List<Callable<BigInteger>> forkFactorials) {
List<Future<BigInteger>> futures = forkJoinPool.invokeAll(forkFactorials);
BigInteger result = BigInteger.ZERO;
for (Future<BigInteger> future : futures) {
try {
result = result.add(future.get());
} catch (InterruptedException | ExecutionException e) {
// exception handling example
throw new RuntimeException(e);
}
}
return result;
}
}

View File

@ -0,0 +1,43 @@
package com.baeldung.concurrent.threadreturnvalue.task.fork;
import static com.baeldung.concurrent.threadreturnvalue.task.FactorialCalculator.factorial;
import java.math.BigInteger;
import java.util.concurrent.RecursiveTask;
public class ForkFactorialTask extends RecursiveTask<BigInteger> {
private final int start;
private final int end;
private final int threshold;
public ForkFactorialTask(int end, int threshold) {
this.start = 1;
this.end = end;
this.threshold = threshold;
}
public ForkFactorialTask(int start, int end, int threshold) {
this.start = start;
this.end = end;
this.threshold = threshold;
}
@Override
protected BigInteger compute() {
BigInteger sum = BigInteger.ONE;
if (end - start > threshold) {
int middle = (end + start) / 2;
return sum.multiply(new ForkFactorialTask(start, middle, threshold).fork()
.join()
.multiply(new ForkFactorialTask(middle + 1, end, threshold).fork()
.join()));
}
return sum.multiply(factorial(BigInteger.valueOf(start), BigInteger.valueOf(end)));
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.concurrent.threadreturnvalue.callable;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.math.BigInteger;
import java.util.Arrays;
import org.junit.jupiter.api.Test;
import com.baeldung.concurrent.threadreturnvalue.task.callable.CallableExecutor;
import com.baeldung.concurrent.threadreturnvalue.task.callable.CallableFactorialTask;
public class CallableUnitTest {
private final CallableExecutor callableExecutor = new CallableExecutor();
@Test
void givenCallableExecutor_whenExecuteFactorial_thenResultOk() {
BigInteger result = callableExecutor.execute(Arrays.asList(new CallableFactorialTask(5), new CallableFactorialTask(3)));
assertEquals(BigInteger.valueOf(126), result);
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.concurrent.threadreturnvalue.completableFuture;
import static com.baeldung.concurrent.threadreturnvalue.task.FactorialCalculator.factorial;
import static java.util.concurrent.CompletableFuture.allOf;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.math.BigInteger;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import org.junit.jupiter.api.Test;
public class CompletableFutureUnitTest {
@Test
void givenCompletableFuture_whenSupplyAsyncFactorial_thenResultOk() throws ExecutionException, InterruptedException {
CompletableFuture<BigInteger> completableFuture = CompletableFuture.supplyAsync(() -> factorial(BigInteger.valueOf(10)));
assertEquals(BigInteger.valueOf(3628800), completableFuture.get());
}
@Test
void givenCompletableFuture_whenComposeTasks_thenResultOk() throws ExecutionException, InterruptedException {
CompletableFuture<BigInteger> completableFuture = CompletableFuture.supplyAsync(() -> factorial(BigInteger.valueOf(3)))
.thenCompose(inputFromFirstTask -> CompletableFuture.supplyAsync(() -> factorial(inputFromFirstTask)));
assertEquals(BigInteger.valueOf(720), completableFuture.get());
}
@Test
void givenCompletableFuture_whenAllOfTasks_thenResultOk() {
CompletableFuture<BigInteger> asyncTask1 = CompletableFuture.supplyAsync(() -> BigInteger.valueOf(5));
CompletableFuture<String> asyncTask2 = CompletableFuture.supplyAsync(() -> "3");
BigInteger result = allOf(asyncTask1, asyncTask2).thenApplyAsync(fn -> factorial(asyncTask1.join()).add(factorial(new BigInteger(asyncTask2.join()))), Executors.newFixedThreadPool(1))
.join();
assertEquals(BigInteger.valueOf(126), result);
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.concurrent.threadreturnvalue.fork;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.math.BigInteger;
import java.util.Arrays;
import org.junit.jupiter.api.Test;
import com.baeldung.concurrent.threadreturnvalue.task.callable.CallableFactorialTask;
import com.baeldung.concurrent.threadreturnvalue.task.fork.ForkExecutor;
import com.baeldung.concurrent.threadreturnvalue.task.fork.ForkFactorialTask;
public class ForkUnitTest {
private final ForkExecutor forkExecutor = new ForkExecutor();
@Test
void givenForkExecutor_whenExecuteRecursiveTask_thenResultOk() {
assertEquals(BigInteger.valueOf(3628800), forkExecutor.execute(new ForkFactorialTask(10, 5)));
}
@Test
void givenForkExecutor_whenExecuteCallable_thenResultOk() {
assertEquals(BigInteger.valueOf(126), forkExecutor.execute(Arrays.asList(new CallableFactorialTask(5), new CallableFactorialTask(3))));
}
}

View File

@ -9,5 +9,5 @@ This module contains articles about basic Java concurrency
- [How to Kill a Java Thread](https://www.baeldung.com/java-thread-stop)
- [ExecutorService Waiting for Threads to Finish](https://www.baeldung.com/java-executor-wait-for-threads)
- [Runnable vs. Callable in Java](https://www.baeldung.com/java-runnable-callable)
- [What is Thread-Safety and How to Achieve it?](https://www.baeldung.com/java-thread-safety)
- [What Is Thread-Safety and How to Achieve It?](https://www.baeldung.com/java-thread-safety)
- [[Next -->]](/core-java-modules/core-java-concurrency-basic-2)

View File

@ -7,7 +7,7 @@ This module contains articles about concurrent Java collections
- [A Guide to ConcurrentMap](http://www.baeldung.com/java-concurrent-map)
- [Guide to PriorityBlockingQueue in Java](http://www.baeldung.com/java-priority-blocking-queue)
- [Avoiding the ConcurrentModificationException in Java](http://www.baeldung.com/java-concurrentmodificationexception)
- [Custom Thread Pools In Java 8 Parallel Streams](http://www.baeldung.com/java-8-parallel-streams-custom-threadpool)
- [Custom Thread Pools in Java 8 Parallel Streams](https://www.baeldung.com/java-8-parallel-streams-custom-threadpool)
- [Guide to DelayQueue](http://www.baeldung.com/java-delay-queue)
- [A Guide to Java SynchronousQueue](http://www.baeldung.com/java-synchronous-queue)
- [Guide to the ConcurrentSkipListMap](http://www.baeldung.com/java-concurrent-skip-list-map)

View File

@ -10,6 +10,6 @@ This module contains articles about date operations in Java.
- [Handling Daylight Savings Time in Java](http://www.baeldung.com/java-daylight-savings)
- [Calculate Age in Java](http://www.baeldung.com/java-get-age)
- [Increment Date in Java](http://www.baeldung.com/java-increment-date)
- [Add Hours To a Date In Java](http://www.baeldung.com/java-add-hours-date)
- [Add Hours to a Date in Java](https://www.baeldung.com/java-add-hours-date)
- [Introduction to Joda-Time](http://www.baeldung.com/joda-time)
- [[Next -->]](/core-java-modules/core-java-date-operations-2)
- [[Next -->]](/core-java-modules/core-java-date-operations-2)

View File

@ -5,10 +5,10 @@ This module contains articles about date operations in Java.
- [Get the Current Date Prior to Java 8](https://www.baeldung.com/java-get-the-current-date-legacy)
- [Skipping Weekends While Adding Days to LocalDate in Java 8](https://www.baeldung.com/java-localdate-add-days-skip-weekends)
- [Checking if Two Java Dates are On the Same Day](https://www.baeldung.com/java-check-two-dates-on-same-day)
- [Checking if Two Java Dates Are on the Same Day](https://www.baeldung.com/java-check-two-dates-on-same-day)
- [Converting Java Date to OffsetDateTime](https://www.baeldung.com/java-convert-date-to-offsetdatetime)
- [How to Set the JVM Time Zone](https://www.baeldung.com/java-jvm-time-zone)
- [How to determine day of week by passing specific date in Java?](https://www.baeldung.com/java-get-day-of-week)
- [How to Determine Day of Week by Passing Specific Date in Java?](https://www.baeldung.com/java-get-day-of-week)
- [Finding Leap Years in Java](https://www.baeldung.com/java-leap-year)
- [Getting the Week Number From Any Date](https://www.baeldung.com/java-get-week-number)
- [Subtract Days from a Date in Java](https://www.baeldung.com/java-subtract-days-from-date)

View File

@ -0,0 +1,98 @@
package com.baeldung.sortdatestrings;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.google.common.collect.Lists;
public class SortDateStringsUnitTest {
private List<String> dtStrings = null;
// @formatter:off
private static final List<String> EXPECTED = Lists.newArrayList(
"01/20/2013 06:16",
"01/20/2013 10:48",
"01/21/2013 10:41",
"01/21/2013 16:37",
"01/21/2013 17:16",
"01/21/2013 17:19",
"01/22/2013 06:19",
"01/22/2013 15:13"
);
// @formatter:on
@BeforeEach
void resetInput() {
// @formatter:off
dtStrings = Lists.newArrayList(
"01/21/2013 10:41",
"01/20/2013 10:48",
"01/22/2013 15:13",
"01/21/2013 16:37",
"01/21/2013 17:16",
"01/21/2013 17:19",
"01/20/2013 06:16",
"01/22/2013 06:19"
);
// @formatter:on
}
@Test
void whenUsingCustomComparator_thenGetExpectedResult() {
DateFormat dfm = new SimpleDateFormat("MM/dd/yyyy HH:mm");
Collections.sort(dtStrings, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
try {
return dfm.parse(o1)
.compareTo(dfm.parse(o2));
} catch (ParseException e) {
throw new IllegalArgumentException(e);
}
}
});
assertEquals(EXPECTED, dtStrings);
}
@Test
void whenUsingListSort_thenGetExpectedResult() {
DateTimeFormatter dfm = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm");
dtStrings.sort(Comparator.comparing(s -> LocalDateTime.parse(s, dfm)));
assertEquals(EXPECTED, dtStrings);
}
@Test
void whenUsingStreamToNewList_thenGetExpectedResult() {
DateTimeFormatter dfm = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm");
List<String> sortedList = dtStrings.stream()
.map(s -> LocalDateTime.parse(s, dfm))
.sorted()
.map(dfm::format)
.collect(Collectors.toList());
assertEquals(EXPECTED, sortedList);
}
@Test
void whenUsingTreeMap_thenGetExpectedResult() {
DateTimeFormatter dfm = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm");
Map<LocalDateTime, String> dateFormatMap = new TreeMap<>();
dtStrings.forEach(s -> dateFormatMap.put(LocalDateTime.parse(s, dfm), s));
List<String> result = new ArrayList<>(dateFormatMap.values());
assertEquals(EXPECTED, result);
}
}

View File

@ -4,12 +4,12 @@ This module contains articles about parsing and formatting Java date and time ob
### Relevant Articles:
- [Check If a String Is a Valid Date in Java](https://www.baeldung.com/java-string-valid-date)
- [RegEx for matching Date Pattern in Java](http://www.baeldung.com/java-date-regular-expressions)
- [Regex for Matching Date Pattern in Java](https://www.baeldung.com/java-date-regular-expressions)
- [Guide to DateTimeFormatter](https://www.baeldung.com/java-datetimeformatter)
- [Format ZonedDateTime to String](https://www.baeldung.com/java-format-zoned-datetime-string)
- [A Guide to SimpleDateFormat](https://www.baeldung.com/java-simple-date-format)
- [Display All Time Zones With GMT And UTC in Java](http://www.baeldung.com/java-time-zones)
- [Convert between String and Timestamp](https://www.baeldung.com/java-string-to-timestamp)
- [Display All Time Zones With GMT and UTC in Java](https://www.baeldung.com/java-time-zones)
- [Convert Between String and Timestamp](https://www.baeldung.com/java-string-to-timestamp)
- [Convert String to Date in Java](http://www.baeldung.com/java-string-to-date)
- [Format a Milliseconds Duration to HH:MM:SS](https://www.baeldung.com/java-ms-to-hhmmss)
- [Format Instant to String in Java](https://www.baeldung.com/java-instant-to-string)

View File

@ -1,9 +1,16 @@
package com.baeldung.readlargefile;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Scanner;
import java.util.stream.Stream;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;
@ -93,6 +100,61 @@ public class ReadLargeFileUnitTest {
logMemory();
}
@Test
public void givenUsingBufferedReader_whenIteratingAFile_thenCorrect() throws IOException {
String fileName = "src/test/resources/myFile";
logMemory();
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
while (br.readLine() != null) {
// do something with each line
}
}
logMemory();
}
@Test
public void givenUsingNewBufferedReader_whenIteratingAFile_thenCorrect() throws IOException {
String fileName = "src/test/resources/myFile";
logMemory();
try (BufferedReader br = java.nio.file.Files.newBufferedReader(Paths.get(fileName))) {
while (br.readLine() != null) {
// do something with each line
}
}
logMemory();
}
@Test
public void givenUsingSeekableByteChannel_whenIteratingAFile_thenCorrect() throws IOException {
String fileName = "src/test/resources/myFile";
logMemory();
try (SeekableByteChannel ch = java.nio.file.Files.newByteChannel(Paths.get(fileName), StandardOpenOption.READ)) {
ByteBuffer bf = ByteBuffer.allocate(1000);
while (ch.read(bf) > 0) {
bf.flip();
// System.out.println(new String(bf.array()));
bf.clear();
}
}
logMemory();
}
@Test
public void givenUsingStreamApi_whenIteratingAFile_thenCorrect() throws IOException {
String fileName = "src/test/resources/myFile";
logMemory();
try (Stream<String> lines = java.nio.file.Files.lines(Paths.get(fileName))) {
lines.forEach(line -> {
// do something with each line
});
}
logMemory();
}
// utils
private final void logMemory() {

View File

@ -12,3 +12,5 @@ This module contains articles about core Java input/output(IO) APIs.
- [Storing Java Scanner Input in an Array](https://www.baeldung.com/java-store-scanner-input-in-array)
- [How to Take Input as String With Spaces in Java Using Scanner?](https://www.baeldung.com/java-scanner-input-with-spaces)
- [Write Console Output to Text File in Java](https://www.baeldung.com/java-write-console-output-file)
- [Whats the difference between Scanner next() and nextLine() methods?](https://www.baeldung.com/java-scanner-next-vs-nextline)
- [Handle NoSuchElementException When Reading a File Through Scanner](https://www.baeldung.com/java-scanner-nosuchelementexception-reading-file)

View File

@ -3,9 +3,9 @@
This module contains articles about core features in the Java language
### Relevant Articles:
- [Java Primitives versus Objects](https://www.baeldung.com/java-primitives-vs-objects)
- [Java Primitives Versus Objects](https://www.baeldung.com/java-primitives-vs-objects)
- [Command-Line Arguments in Java](https://www.baeldung.com/java-command-line-arguments)
- [What is a POJO Class?](https://www.baeldung.com/java-pojo-class)
- [What Is a Pojo Class?](https://www.baeldung.com/java-pojo-class)
- [Java Default Parameters Using Method Overloading](https://www.baeldung.com/java-default-parameters-method-overloading)
- [How to Return Multiple Values From a Java Method](https://www.baeldung.com/java-method-return-multiple-values)
- [Guide to the Java finally Keyword](https://www.baeldung.com/java-finally-keyword)

View File

@ -4,7 +4,7 @@ This module contains articles about core features in the Java language
- [Class.isInstance vs Class.isAssignableFrom and instanceof](https://www.baeldung.com/java-isinstance-isassignablefrom)
- [Converting a Java String Into a Boolean](https://www.baeldung.com/java-string-to-boolean)
- [When are Static Variables Initialized in Java?](https://www.baeldung.com/java-static-variables-initialization)
- [When Are Static Variables Initialized in Java?](https://www.baeldung.com/java-static-variables-initialization)
- [Checking if a Class Exists in Java](https://www.baeldung.com/java-check-class-exists)
- [The Difference Between a.getClass() and A.class in Java](https://www.baeldung.com/java-getclass-vs-class)
- [Constants in Java: Patterns and Anti-Patterns](https://www.baeldung.com/java-constants-good-practices)

View File

@ -6,7 +6,7 @@
- [Calculate Factorial in Java](https://www.baeldung.com/java-calculate-factorial)
- [Generate Combinations in Java](https://www.baeldung.com/java-combinations-algorithm)
- [Check If Two Rectangles Overlap In Java](https://www.baeldung.com/java-check-if-two-rectangles-overlap)
- [Check if Two Rectangles Overlap in Java](https://www.baeldung.com/java-check-if-two-rectangles-overlap)
- [Calculate the Distance Between Two Points in Java](https://www.baeldung.com/java-distance-between-two-points)
- [Find the Intersection of Two Lines in Java](https://www.baeldung.com/java-intersection-of-two-lines)
- [Round Up to the Nearest Hundred in Java](https://www.baeldung.com/java-round-up-nearest-hundred)

View File

@ -8,7 +8,7 @@ This module contains articles about types in Java
- [Guide to the this Java Keyword](https://www.baeldung.com/java-this)
- [Nested Classes in Java](https://www.baeldung.com/java-nested-classes)
- [Marker Interfaces in Java](https://www.baeldung.com/java-marker-interfaces)
- [Iterating over Enum Values in Java](https://www.baeldung.com/java-enum-iteration)
- [Iterating Over Enum Values in Java](https://www.baeldung.com/java-enum-iteration)
- [Attaching Values to Java Enum](https://www.baeldung.com/java-enum-values)
- [A Guide to Java Enums](https://www.baeldung.com/a-guide-to-java-enums)
- [Determine if an Object Is of Primitive Type](https://www.baeldung.com/java-object-primitive-type)

View File

@ -4,7 +4,7 @@ This module contains articles about Java operators
## Relevant Articles:
- [Guide to the Diamond Operator in Java](https://www.baeldung.com/java-diamond-operator)
- [Ternary Operator In Java](https://www.baeldung.com/java-ternary-operator)
- [Ternary Operator in Java](https://www.baeldung.com/java-ternary-operator)
- [The Modulo Operator in Java](https://www.baeldung.com/modulo-java)
- [Java instanceof Operator](https://www.baeldung.com/java-instanceof)
- [A Guide to Increment and Decrement Unary Operators in Java](https://www.baeldung.com/java-unary-operators)

View File

@ -5,7 +5,7 @@ This module contains articles about core features in the Java language
### Relevant Articles:
- [Generate equals() and hashCode() with Eclipse](https://www.baeldung.com/java-eclipse-equals-and-hashcode)
- [Comparator and Comparable in Java](https://www.baeldung.com/java-comparator-comparable)
- [Recursion In Java](https://www.baeldung.com/java-recursion)
- [Recursion in Java](https://www.baeldung.com/java-recursion)
- [A Guide to the finalize Method in Java](https://www.baeldung.com/java-finalize)
- [Quick Guide to java.lang.System](https://www.baeldung.com/java-lang-system)
- [Using Java Assertions](https://www.baeldung.com/java-assert)

View File

@ -12,6 +12,6 @@ This module contains articles about networking in Java
- [Authentication with HttpUrlConnection](https://www.baeldung.com/java-http-url-connection)
- [Download a File From an URL in Java](https://www.baeldung.com/java-download-file)
- [Handling java.net.ConnectException](https://www.baeldung.com/java-net-connectexception)
- [Getting MAC addresses in Java](https://www.baeldung.com/java-mac-address)
- [Getting MAC Addresses in Java](https://www.baeldung.com/java-mac-address)
- [Sending Emails with Attachments in Java](https://www.baeldung.com/java-send-emails-attachments)
- [[<-- Prev]](/core-java-modules/core-java-networking)

View File

@ -6,12 +6,12 @@ This module contains articles about networking in Java
- [Connecting Through Proxy Servers in Core Java](https://www.baeldung.com/java-connect-via-proxy-server)
- [Broadcasting and Multicasting in Java](http://www.baeldung.com/java-broadcast-multicast)
- [A Guide To UDP In Java](http://www.baeldung.com/udp-in-java)
- [A Guide To HTTP Cookies In Java](http://www.baeldung.com/cookies-java)
- [A Guide to UDP In Java](https://www.baeldung.com/udp-in-java)
- [A Guide to HTTP Cookies in Java](https://www.baeldung.com/cookies-java)
- [A Guide to the Java URL](http://www.baeldung.com/java-url)
- [Working with Network Interfaces in Java](http://www.baeldung.com/java-network-interfaces)
- [A Guide to Java Sockets](http://www.baeldung.com/a-guide-to-java-sockets)
- [Guide to Java URL Encoding/Decoding](http://www.baeldung.com/java-url-encoding-decoding)
- [Difference between URL and URI](http://www.baeldung.com/java-url-vs-uri)
- [Difference Between URL and URI](https://www.baeldung.com/java-url-vs-uri)
- [Read an InputStream using the Java Server Socket](https://www.baeldung.com/java-inputstream-server-socket)
- [[More -->]](/core-java-modules/core-java-networking-2)

View File

@ -3,6 +3,5 @@
This module contains articles about performance of Java applications
### Relevant Articles:
- [Possible Root Causes for High CPU Usage in Java](https://www.baeldung.com/java-high-cpu-usage-causes)
- [External Debugging With JMXTerm](https://www.baeldung.com/java-jmxterm-external-debugging)
- [Create and Detect Memory Leaks in Java](https://www.baeldung.com/java-create-detect-memory-leaks)

View File

@ -13,5 +13,3 @@ This module contains articles about performance of Java applications
- [Capturing a Java Thread Dump](https://www.baeldung.com/java-thread-dump)
- [JMX Ports](https://www.baeldung.com/jmx-ports)
- [Calling JMX MBean Method From a Shell Script](https://www.baeldung.com/jmx-mbean-shell-access)
- [External Debugging With JMXTerm](https://www.baeldung.com/java-jmxterm-external-debugging)
- [Create and Detect Memory Leaks in Java](https://www.baeldung.com/java-create-detect-memory-leaks)

View File

@ -1,2 +1,2 @@
## Relevant Articles
- [Overridding hashCode() And equals() For Records](https://www.baeldung.com/java-override-hashcode-equals-records)
- [Overriding hashCode() And equals() For Records](https://www.baeldung.com/java-override-hashcode-equals-records)

View File

@ -4,20 +4,24 @@ import java.util.Objects;
record Movie(String name, Integer yearOfRelease, String distributor) {
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other == null) {
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other == null) {
return false;
}
if (!(other instanceof Movie)) {
return false;
}
Movie movie = (Movie) other;
if (movie.name.equals(this.name) && movie.yearOfRelease.equals(this.yearOfRelease)) {
return true;
}
return false;
}
Movie movie = (Movie) other;
if (movie.name.equals(this.name) && movie.yearOfRelease.equals(this.yearOfRelease)) {
return true;
}
return false;
}
@Override
public int hashCode() {

View File

@ -1,10 +0,0 @@
### Relevant Articles:
- [Reading the Value of private Fields from a Different Class in Java](https://www.baeldung.com/java-reflection-read-private-field-value)
- [Set Field Value With Reflection](https://www.baeldung.com/java-set-private-field-value)
- [Checking If a Method is Static Using Reflection in Java](https://www.baeldung.com/java-check-method-is-static)
- [Checking if a Java Class is abstract Using Reflection](https://www.baeldung.com/java-reflection-is-class-abstract)
- [Invoking a Private Method in Java](https://www.baeldung.com/java-call-private-method)
- [Finding All Classes in a Java Package](https://www.baeldung.com/java-find-all-classes-in-package)
- [Invoke a Static Method Using Java Reflection API](https://www.baeldung.com/java-invoke-static-method-reflection)
- [What Is the JDK com.sun.proxy.$Proxy Class?](https://www.baeldung.com/jdk-com-sun-proxy)

View File

@ -1,59 +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>
<artifactId>core-java-reflection-private-constructor</artifactId>
<name>core-java-reflection-private-constructor</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>${reflections.version}</version>
</dependency>
</dependencies>
<build>
<finalName>core-java-reflection-private-constructor</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>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${source.version}</source>
<target>${target.version}</target>
<compilerArgument>-parameters</compilerArgument>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<reflections.version>0.9.12</reflections.version>
<source.version>1.8</source.version>
<target.version>1.8</target.version>
<spring.version>5.3.4</spring.version>
</properties>
</project>

View File

@ -1,8 +0,0 @@
package com.baeldung.reflection;
public class PrivateConstructorClass {
private PrivateConstructorClass() {
System.out.println("Used the private constructor!");
}
}

View File

@ -1,17 +0,0 @@
package com.baeldung.reflection;
import java.lang.reflect.Constructor;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class PrivateConstructorUnitTest {
@Test
public void whenConstructorIsPrivate_thenInstanceSuccess() throws Exception {
Constructor<PrivateConstructorClass> pcc = PrivateConstructorClass.class.getDeclaredConstructor();
pcc.setAccessible(true);
PrivateConstructorClass privateConstructorInstance = pcc.newInstance();
Assertions.assertTrue(privateConstructorInstance instanceof PrivateConstructorClass);
}
}

View File

@ -3,7 +3,7 @@
- [Void Type in Java](https://www.baeldung.com/java-void-type)
- [Retrieve Fields from a Java Class Using Reflection](https://www.baeldung.com/java-reflection-class-fields)
- [Method Parameter Reflection in Java](http://www.baeldung.com/java-parameter-reflection)
- [Changing Annotation Parameters At Runtime](http://www.baeldung.com/java-reflection-change-annotation-params)
- [Changing Annotation Parameters at Runtime](https://www.baeldung.com/java-reflection-change-annotation-params)
- [Dynamic Proxies in Java](http://www.baeldung.com/java-dynamic-proxies)
- [What Causes java.lang.reflect.InvocationTargetException?](https://www.baeldung.com/java-lang-reflect-invocationtargetexception)
- [How to Get a Name of a Method Being Executed?](http://www.baeldung.com/java-name-of-executing-method)

View File

@ -4,7 +4,7 @@ This module contains articles about core Java Security
### Relevant Articles:
- [Guide To The Java Authentication And Authorization Service (JAAS)](https://www.baeldung.com/java-authentication-authorization-service)
- [Guide to the Java Authentication And Authorization Service (JAAS)](https://www.baeldung.com/java-authentication-authorization-service)
- [MD5 Hashing in Java](http://www.baeldung.com/java-md5)
- [Hashing a Password in Java](https://www.baeldung.com/java-password-hashing)
- [SHA-256 and SHA3-256 Hashing in Java](https://www.baeldung.com/sha-256-hashing-java)

View File

@ -6,4 +6,5 @@
- [Introduction to Java Serialization](http://www.baeldung.com/java-serialization)
- [Deserialization Vulnerabilities in Java](https://www.baeldung.com/java-deserialization-vulnerabilities)
- [Serialization Validation in Java](https://www.baeldung.com/java-validate-serializable)
- [What is the serialVersionUID?](http://www.baeldung.com/java-serial-version-uid)
- [What Is the serialVersionUID?](https://www.baeldung.com/java-serial-version-uid)
- [Java Serialization: readObject() vs. readResolve()](https://www.baeldung.com/java-serialization-readobject-vs-readresolve)

View File

@ -12,5 +12,5 @@ This module contains articles about the Stream API in Java.
- [Java Stream Filter with Lambda Expression](https://www.baeldung.com/java-stream-filter-lambda)
- [Counting Matches on a Stream Filter](https://www.baeldung.com/java-stream-filter-count)
- [Summing Numbers with Java Streams](https://www.baeldung.com/java-stream-sum)
- [How to Find all Getters Returning Null](https://www.baeldung.com/java-getters-returning-null)
- [How to Find All Getters Returning Null](https://www.baeldung.com/java-getters-returning-null)
- More articles: [[next -->]](/../core-java-streams-2)

View File

@ -6,7 +6,7 @@ This module contains articles about string-related algorithms.
- [How to Remove the Last Character of a String?](https://www.baeldung.com/java-remove-last-character-of-string)
- [Add a Character to a String at a Given Position](https://www.baeldung.com/java-add-character-to-string)
- [Java Check a String for Lowercase/Uppercase Letter, Special Character and Digit](https://www.baeldung.com/java-lowercase-uppercase-special-character-digit-regex)
- [Remove or Replace part of a String in Java](https://www.baeldung.com/java-remove-replace-string-part)
- [Remove or Replace Part of a String in Java](https://www.baeldung.com/java-remove-replace-string-part)
- [Replace a Character at a Specific Index in a String in Java](https://www.baeldung.com/java-replace-character-at-index)
- [Join Array of Primitives with Separator in Java](https://www.baeldung.com/java-join-primitive-array)
- [Pad a String with Zeros or Spaces in Java](https://www.baeldung.com/java-pad-string)

View File

@ -5,7 +5,7 @@ This module contains articles about string-related algorithms.
### Relevant Articles:
- [Generating a Java String of N Repeated Characters](https://www.baeldung.com/java-string-of-repeated-characters)
- [Check if Two Strings are Anagrams in Java](https://www.baeldung.com/java-strings-anagrams)
- [Check if Two Strings Are Anagrams in Java](https://www.baeldung.com/java-strings-anagrams)
- [Email Validation in Java](https://www.baeldung.com/java-email-validation-regex)
- [Check if the First Letter of a String Is Uppercase](https://www.baeldung.com/java-check-first-letter-uppercase)
- [Find the First Non Repeating Character in a String in Java](https://www.baeldung.com/java-find-the-first-non-repeating-character)

View File

@ -3,13 +3,13 @@
This module contains articles about string-related algorithms.
### Relevant Articles:
- [Check if a String is a Palindrome in Java](https://www.baeldung.com/java-palindrome)
- [Check if a String Is a Palindrome in Java](https://www.baeldung.com/java-palindrome)
- [Count Occurrences of a Char in a String](https://www.baeldung.com/java-count-chars)
- [Using indexOf to Find All Occurrences of a Word in a String](https://www.baeldung.com/java-indexof-find-string-occurrences)
- [Removing Stopwords from a String in Java](https://www.baeldung.com/java-string-remove-stopwords)
- [Removing Repeated Characters from a String](https://www.baeldung.com/java-remove-repeated-char)
- [How to Reverse a String in Java](https://www.baeldung.com/java-reverse-string)
- [Check if a String is a Pangram in Java](https://www.baeldung.com/java-string-pangram)
- [Check if a String Is a Pangram in Java](https://www.baeldung.com/java-string-pangram)
- [Check If a String Contains Multiple Keywords in Java](https://www.baeldung.com/string-contains-multiple-words)
- [Checking If a String Is a Repeated Substring](https://www.baeldung.com/java-repeated-substring)
- [Remove Emojis from a Java String](https://www.baeldung.com/java-string-remove-emojis)

View File

@ -3,7 +3,7 @@
This module contains articles about string operations.
### Relevant Articles:
- [Concatenating Strings In Java](https://www.baeldung.com/java-strings-concatenation)
- [Concatenating Strings in Java](https://www.baeldung.com/java-strings-concatenation)
- [Checking for Empty or Blank Strings in Java](https://www.baeldung.com/java-blank-empty-strings)
- [String Initialization in Java](https://www.baeldung.com/java-string-initialization)
- [String toLowerCase and toUpperCase Methods in Java](https://www.baeldung.com/java-string-convert-case)

View File

@ -10,5 +10,4 @@
- [Guide to Splitting a String by Whitespace in Java](https://www.baeldung.com/java-splitting-a-string-by-whitespace)
- [Check if the First Letter of a String Is a Number](https://www.baeldung.com/java-check-if-string-starts-with-number)
- [Print “” Quotes Around a String in Java](https://www.baeldung.com/java-string-print-quotes)
- [Remove Punctuation From a String in Java](https://www.baeldung.com/java-remove-punctuation-from-string)
- [Find the Longest Word in a Given String in Java](https://www.baeldung.com/java-longest-word-string)
- [Remove Punctuation From a String in Java](https://www.baeldung.com/java-remove-punctuation-from-string)

View File

@ -0,0 +1,4 @@
### Relevant Articles:
- [Find the Longest Word in a Given String in Java](https://www.baeldung.com/java-longest-word-string)

View File

@ -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>core-java-string-operations-6</artifactId>
<name>core-java-string-operations-6</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
</project>

View File

@ -137,6 +137,7 @@
<module>core-java-string-conversions-3</module>
<module>core-java-string-operations</module>
<module>core-java-string-operations-2</module>
<module>core-java-string-operations-6</module>
<module>core-java-regex</module>
<module>core-java-regex-2</module>
<module>core-java-uuid</module>

View File

@ -0,0 +1,42 @@
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store

View File

@ -0,0 +1,23 @@
plugins {
id 'java'
id("com.github.bjornvester.wsdl2java") version "1.2"
}
repositories {
mavenCentral()
}
dependencies {
implementation 'com.sun.xml.ws:jaxws-ri:4.0.1'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.2'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.2'
}
test {
useJUnitPlatform()
}
wsdl2java {
cxfVersion.set("3.4.4")
}

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