Merge pull request #1 from eugenp/master

Updating local ref
This commit is contained in:
Sallo Szrajbman 2021-02-13 11:47:00 +01:00 committed by GitHub
commit 31e7597576
1703 changed files with 10609 additions and 2264 deletions

View File

@ -51,7 +51,7 @@
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
<scope>provided</scope>
<exclusions>

View File

@ -89,7 +89,6 @@
<properties>
<json-simple.version>1.1.1</json-simple.version>
<commons-io.version>2.5</commons-io.version>
<aws-lambda-java-events.version>1.3.0</aws-lambda-java-events.version>
<aws-lambda-java-core.version>1.2.0</aws-lambda-java-core.version>
<gson.version>2.8.2</gson.version>

View File

@ -154,7 +154,6 @@
<properties>
<blade-mvc.version>2.0.14.RELEASE</blade-mvc.version>
<bootstrap.version>4.2.1</bootstrap.version>
<commons-lang3.version>3.8.1</commons-lang3.version>
<lombok.version>1.18.4</lombok.version>
<httpclient.version>4.5.6</httpclient.version>
<httpmime.version>4.5.6</httpmime.version>

View File

@ -5,7 +5,7 @@ This module contains articles about Java 10 core features
### Relevant Articles:
- [Java 10 LocalVariable Type-Inference](http://www.baeldung.com/java-10-local-variable-type-inference)
- [Guide to Java 10](http://www.baeldung.com/java-10-overview)
- [New Features in Java 10](https://www.baeldung.com/java-10-overview)
- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)
- [Deep Dive Into the New Java JIT Compiler Graal](https://www.baeldung.com/graal-java-jit-compiler)
- [Copying Sets in Java](https://www.baeldung.com/java-copy-sets)

View File

@ -6,3 +6,4 @@ This module contains articles about Java 11 core features
- [Guide to Java 8 Optional](https://www.baeldung.com/java-optional)
- [Guide to Java Reflection](http://www.baeldung.com/java-reflection)
- [Guide to Java 8s Collectors](https://www.baeldung.com/java-8-collectors)
- [New Features in Java 11](https://www.baeldung.com/java-11-new-features)

View File

@ -28,6 +28,29 @@
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mock-server</groupId>
<artifactId>mockserver-junit-jupiter</artifactId>
<version>${mockserver.version}</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
@ -48,7 +71,9 @@
<maven.compiler.source.version>11</maven.compiler.source.version>
<maven.compiler.target.version>11</maven.compiler.target.version>
<guava.version>29.0-jre</guava.version>
<junit.jupiter.version>5.7.0</junit.jupiter.version>
<assertj.version>3.17.2</assertj.version>
<mockserver.version>5.11.1</mockserver.version>
</properties>
</project>

View File

@ -0,0 +1,17 @@
package com.baeldung.features;
public class MainClass {
private static boolean mainPrivateMethod() {
return true;
}
public static class NestedClass {
boolean nestedPublicMethod() {
return mainPrivateMethod();
}
}
}

View File

@ -0,0 +1,54 @@
package com.baeldung.features;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.mockserver.integration.ClientAndServer;
import org.mockserver.model.HttpStatusCode;
import org.mockserver.socket.PortFactory;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
class HttpClientIntegrationTest {
private static ClientAndServer mockServer;
private static int port;
@BeforeAll
static void startServer() {
port = PortFactory.findFreePort();
mockServer = startClientAndServer(port);
mockServer.when(new org.mockserver.model.HttpRequest().withMethod("GET"))
.respond(new org.mockserver.model.HttpResponse()
.withStatusCode(HttpStatusCode.OK_200.code())
.withBody("Hello from the server!"));
}
@AfterAll
static void stopServer() {
mockServer.stop();
}
@Test
void givenSampleHttpRequest_whenRequestIsSent_thenServerResponseIsReceived() throws IOException, InterruptedException {
HttpClient httpClient = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.connectTimeout(Duration.ofSeconds(20))
.build();
HttpRequest httpRequest = HttpRequest.newBuilder()
.GET()
.uri(URI.create("http://localhost:" + port))
.build();
HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
assertThat(httpResponse.body()).isEqualTo("Hello from the server!");
}
}

View File

@ -0,0 +1,61 @@
package com.baeldung.features;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import javax.annotation.Nonnull;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
class JavaElevenFeaturesUnitTest {
@Test
void givenMultilineString_whenExtractingNonBlankStrippedLines_thenLinesAreReturned() {
String multilineString = "Baeldung helps \n \n developers \n explore Java.";
List<String> lines = multilineString.lines()
.filter(line -> !line.isBlank())
.map(String::strip)
.collect(Collectors.toList());
assertThat(lines).containsExactly("Baeldung helps", "developers", "explore Java.");
}
@Test
void givenTemporaryFile_whenReadingStringContent_thenContentIsReturned(@TempDir Path tempDir) throws IOException {
Path filePath = Files.writeString(Files.createTempFile(tempDir, "demo", ".txt"), "Sample text");
String fileContent = Files.readString(filePath);
assertThat(fileContent).isEqualTo("Sample text");
}
@Test
void givenSampleList_whenConvertingToArray_thenItemsRemainUnchanged() {
List<String> sampleList = Arrays.asList("Java", "Kotlin");
String[] sampleArray = sampleList.toArray(String[]::new);
assertThat(sampleArray).containsExactly("Java", "Kotlin");
}
@Test
void givenSampleList_whenConvertingToUppercaseString_thenUppercaseIsReturned() {
List<String> sampleList = Arrays.asList("Java", "Kotlin");
String resultString = sampleList.stream()
.map((@Nonnull var x) -> x.toUpperCase())
.collect(Collectors.joining(", "));
assertThat(resultString).isEqualTo("JAVA, KOTLIN");
}
@Test
void givenSampleList_whenExtractingNonBlankValues_thenOnlyNonBlanksAreReturned() {
List<String> sampleList = Arrays.asList("Java", "\n \n", "Kotlin", " ");
List<String> withoutBlanks = sampleList.stream()
.filter(Predicate.not(String::isBlank))
.collect(Collectors.toList());
assertThat(withoutBlanks).containsExactly("Java", "Kotlin");
}
}

View File

@ -0,0 +1,37 @@
package com.baeldung.features;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
class NestedClassesUnitTest {
@Test
public void giveNestedClass_whenCallingMainClassPrivateMethod_thenNoExceptionIsThrown() {
MainClass.NestedClass nestedInstance = new MainClass.NestedClass();
assertThat(nestedInstance.nestedPublicMethod()).isTrue();
}
@Test
public void giveNestedClass_whenCheckingNestmate_thenNestedClassIsReturned() {
assertThat(MainClass.class.isNestmateOf(MainClass.NestedClass.class)).isTrue();
}
@Test
public void giveNestedClass_whenCheckingNestHost_thenMainClassIsReturned() {
assertThat(MainClass.NestedClass.class.getNestHost()).isEqualTo(MainClass.class);
}
@Test
public void giveNestedClass_whenCheckingNestMembers_thenNestMembersAreReturned() {
Set<String> nestedMembers = Arrays.stream(MainClass.NestedClass.class.getNestMembers())
.map(Class::getName)
.collect(Collectors.toSet());
assertThat(nestedMembers).contains(MainClass.class.getName(), MainClass.NestedClass.class.getName());
}
}

View File

@ -64,7 +64,7 @@ public class HttpClientUnitTest {
.send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_MOVED_PERM));
assertThat(response.body(), containsString("https://stackoverflow.com/"));
assertTrue(response.headers().map().get("location").stream().anyMatch("https://stackoverflow.com/"::equals));
}
@Test

View File

@ -18,6 +18,7 @@ import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import org.junit.Test;
import org.junit.jupiter.api.Disabled;
public class HttpRequestUnitTest {
@ -48,7 +49,12 @@ public class HttpRequestUnitTest {
assertThat(response.version(), equalTo(HttpClient.Version.HTTP_2));
}
@Test
/*
* This test will fail as soon as the given URL returns a HTTP 2 response.
* Therefore, let's leave it commented out.
* */
@Test
@Disabled
public void shouldFallbackToHttp1_1WhenWebsiteDoesNotUseHttp2() throws IOException, InterruptedException, URISyntaxException, NoSuchAlgorithmException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/get"))

View File

@ -1,4 +1,4 @@
## Relevant Articles:
- [String API Updates in Java 12](https://www.baeldung.com/java12-string-api)
- [New Features in Java 12](https://www.baeldung.com/java-12-new-features)

View File

@ -0,0 +1,21 @@
package java.com.baeldung.newfeatures;
import org.junit.Test;
import java.text.NumberFormat;
import java.util.Locale;
import static org.junit.Assert.assertEquals;
public class CompactNumbersUnitTest {
@Test
public void givenNumber_thenCompactValues() {
NumberFormat likesShort = NumberFormat.getCompactNumberInstance(new Locale("en", "US"), NumberFormat.Style.SHORT);
likesShort.setMaximumFractionDigits(2);
assertEquals("2.59K", likesShort.format(2592));
NumberFormat likesLong = NumberFormat.getCompactNumberInstance(new Locale("en", "US"), NumberFormat.Style.LONG);
likesLong.setMaximumFractionDigits(2);
assertEquals("2.59 thousand", likesShort.format(2592));
}
}

View File

@ -0,0 +1,32 @@
package java.com.baeldung.newfeatures;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.junit.Assert.assertEquals;
public class FileMismatchUnitTest {
@Test
public void givenIdenticalFiles_thenShouldNotFindMismatch() throws IOException {
Path filePath1 = Files.createTempFile("file1", ".txt");
Path filePath2 = Files.createTempFile("file2", ".txt");
Files.writeString(filePath1, "Java 12 Article");
Files.writeString(filePath2, "Java 12 Article");
long mismatch = Files.mismatch(filePath1, filePath2);
assertEquals(-1, mismatch);
}
@Test
public void givenDifferentFiles_thenShouldFindMismatch() throws IOException {
Path filePath3 = Files.createTempFile("file3", ".txt");
Path filePath4 = Files.createTempFile("file4", ".txt");
Files.writeString(filePath3, "Java 12 Article");
Files.writeString(filePath4, "Java 12 Tutorial");
long mismatch = Files.mismatch(filePath3, filePath4);
assertEquals(8, mismatch);
}
}

View File

@ -0,0 +1,15 @@
package java.com.baeldung.newfeatures;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class StringUnitTest {
@Test
public void givenString_thenRevertValue() {
String text = "Baeldung";
String transformed = text.transform(value -> new StringBuilder(value).reverse().toString());
assertEquals("gnudleaB", transformed);
}
}

View File

@ -0,0 +1,18 @@
package java.com.baeldung.newfeatures;
import org.junit.Test;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
public class TeeingCollectorUnitTest {
@Test
public void givenSetOfNumbers_thenCalculateAverage() {
double mean = Stream.of(1, 2, 3, 4, 5)
.collect(Collectors.teeing(Collectors.summingDouble(i -> i), Collectors.counting(), (sum, count) -> sum / count));
assertEquals(3.0, mean);
}
}

View File

@ -1,4 +1,4 @@
### Relevant articles:
- [Java Switch Statement](https://www.baeldung.com/java-switch)
- [New Java 13 Features](https://www.baeldung.com/java-13-new-features)
- [New Features in Java 13](https://www.baeldung.com/java-13-new-features)

View File

@ -10,3 +10,4 @@ This module contains articles about Java 14.
- [Helpful NullPointerExceptions in Java 14](https://www.baeldung.com/java-14-nullpointerexception)
- [Foreign Memory Access API in Java 14](https://www.baeldung.com/java-foreign-memory-access)
- [Java 14 Record Keyword](https://www.baeldung.com/java-record-keyword)
- [New Features in Java 14](https://www.baeldung.com/java-14-new-features)

View File

@ -44,6 +44,8 @@
<configuration>
<release>${maven.compiler.release}</release>
<compilerArgs>--enable-preview</compilerArgs>
<source>14</source>
<target>14</target>
</configuration>
</plugin>
<plugin>

View File

@ -0,0 +1,26 @@
package com.baeldung.java14.newfeatues;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class MultilineUnitTest {
@SuppressWarnings("preview")
String multiline = """
A quick brown fox jumps over a lazy dog; \
the lazy dog howls loudly.""";
@SuppressWarnings("preview")
String anotherMultiline = """
A quick brown fox jumps over a lazy dog;
the lazy dog howls loudly.""";
@Test
public void givenMultilineString_whenSlashUsed_thenNoNewLine() {
assertFalse(multiline.contains("\n"));
assertTrue(anotherMultiline.contains("\n"));
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.java14.newfeatues;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class RecordUnitTest {
@SuppressWarnings("preview")
public record User(int id, String password) {
};
private User user1 = new User(0, "UserOne");
@Test
public void givenRecord_whenObjInitialized_thenValuesCanBeFetchedWithGetters() {
assertEquals(0, user1.id());
assertEquals("UserOne", user1.password());
}
@Test
public void whenRecord_thenEqualsImplemented() {
User user2 = user1;
assertEquals(user1, user2);
}
@Test
public void whenRecord_thenToStringImplemented() {
assertTrue(user1.toString()
.contains("UserOne"));
}
}

View File

@ -0,0 +1,50 @@
package com.baeldung.java14.newfeatues;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class SwitchExprUnitTest {
@Test
public void givenDay_whenSunday_thenWeekend() {
assertTrue(isTodayHolidayInJava8("SUNDAY"));
assertTrue(isTodayHolidayInJava14("SUNDAY"));
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> isTodayHolidayInJava8("SOMEDAY"));
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> isTodayHolidayInJava14("SOMEDAY"));
}
private boolean isTodayHolidayInJava8(String day) {
boolean isTodayHoliday;
switch (day) {
case "MONDAY":
case "TUESDAY":
case "WEDNESDAY":
case "THURSDAY":
case "FRIDAY":
isTodayHoliday = false;
break;
case "SATURDAY":
case "SUNDAY":
isTodayHoliday = true;
break;
default:
throw new IllegalArgumentException("What's a " + day);
}
return isTodayHoliday;
}
private boolean isTodayHolidayInJava14(String day) {
return switch (day) {
case "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY" -> false;
case "SATURDAY", "SUNDAY" -> true;
default -> throw new IllegalArgumentException("What's a " + day);
};
}
}

View File

@ -20,7 +20,7 @@
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${apache-commons-lang3.version}</version>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
@ -68,7 +68,6 @@
<properties>
<maven.compiler.release>15</maven.compiler.release>
<apache-commons-lang3.version>3.11</apache-commons-lang3.version>
<assertj.version>3.17.2</assertj.version>
<maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
<surefire.plugin.version>3.0.0-M3</surefire.plugin.version>

View File

@ -2,8 +2,7 @@ package com.baeldung.java9.modules;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.collection.IsEmptyCollection.empty;
import static org.junit.Assert.*;
@ -74,7 +73,6 @@ public class ModuleAPIUnitTest {
ModuleLayer javaBaseModuleLayer = javaBaseModule.getLayer();
assertTrue(javaBaseModuleLayer.configuration().findModule(JAVA_BASE_MODULE_NAME).isPresent());
assertThat(javaBaseModuleLayer.configuration().modules().size(), is(78));
assertTrue(javaBaseModuleLayer.parents().get(0).configuration().parents().isEmpty());
}
@ -108,8 +106,7 @@ public class ModuleAPIUnitTest {
.collect(Collectors.toSet());
assertThat(javaBaseRequires, empty());
assertThat(javaSqlRequires.size(), is(3));
assertThat(javaSqlRequiresNames, containsInAnyOrder("java.base", "java.xml", "java.logging"));
assertThat(javaSqlRequiresNames, hasItems("java.base", "java.xml", "java.logging"));
}
@Test
@ -127,16 +124,13 @@ public class ModuleAPIUnitTest {
@Test
public void givenModules_whenAccessingModuleDescriptorExports_thenExportsAreReturned() {
Set<Exports> javaBaseExports = javaBaseModule.getDescriptor().exports();
Set<Exports> javaSqlExports = javaSqlModule.getDescriptor().exports();
Set<String> javaSqlExportsSource = javaSqlExports.stream()
.map(Exports::source)
.collect(Collectors.toSet());
assertThat(javaBaseExports.size(), is(108));
assertThat(javaSqlExports.size(), is(3));
assertThat(javaSqlExportsSource, containsInAnyOrder("java.sql", "javax.transaction.xa", "javax.sql"));
assertThat(javaSqlExportsSource, hasItems("java.sql", "javax.sql"));
}
@Test
@ -144,7 +138,6 @@ public class ModuleAPIUnitTest {
Set<String> javaBaseUses = javaBaseModule.getDescriptor().uses();
Set<String> javaSqlUses = javaSqlModule.getDescriptor().uses();
assertThat(javaBaseUses.size(), is(34));
assertThat(javaSqlUses, contains("java.sql.Driver"));
}

View File

@ -4,7 +4,7 @@ This module contains articles about core Java features that have been introduced
### Relevant Articles:
- [Java 9 New Features](https://www.baeldung.com/new-java-9)
- [New Features in Java 9](https://www.baeldung.com/new-java-9)
- [Java 9 Variable Handles Demystified](http://www.baeldung.com/java-variable-handles)
- [Exploring the New HTTP Client in Java 9 and 11](http://www.baeldung.com/java-9-http-client)
- [Multi-Release Jar Files](https://www.baeldung.com/java-multi-release-jar)

View File

@ -47,12 +47,12 @@
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.11</version>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.7</version>
<version>${commons-io.version}</version>
</dependency>
</dependencies>

View File

@ -29,8 +29,6 @@
</dependencies>
<properties>
<commons-lang3.version>3.9</commons-lang3.version>
<assertj-core.version>3.10.0</assertj-core.version>
</properties>
</project>

View File

@ -68,11 +68,7 @@
<properties>
<shade.plugin.version>3.2.0</shade.plugin.version>
<commons-lang3.version>3.9</commons-lang3.version>
<jmh.version>1.19</jmh.version>
<assertj-core.version>3.10.0</assertj-core.version>
</properties>
</project>

View File

@ -76,12 +76,8 @@
<properties>
<shade.plugin.version>3.2.0</shade.plugin.version>
<commons-lang3.version>3.9</commons-lang3.version>
<guava.version>28.2-jre</guava.version>
<jmh.version>1.19</jmh.version>
<assertj-core.version>3.10.0</assertj-core.version>
</properties>
</project>

View File

@ -3,4 +3,4 @@
This module contains articles about Java Character Class
### Relevant Articles:
- Character#isAlphabetic vs Character#isLetter
- [Character#isAlphabetic vs. Character#isLetter](https://www.baeldung.com/java-character-isletter-isalphabetic)

View File

@ -3,35 +3,36 @@ package com.baeldung.character;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertEquals;
public class CharacterGeneralCategoryTypeUnitTest {
@Test
public void givenACharacter_whenUpperCaseLetter_thenAssertTrue() {
assertTrue(Character.getType('U') == Character.UPPERCASE_LETTER);
assertEquals(Character.UPPERCASE_LETTER, Character.getType('U'));
}
@Test
public void givenACharacter_whenLowerCaseLetter_thenAssertTrue() {
assertTrue(Character.getType('u') == Character.LOWERCASE_LETTER);
assertEquals(Character.LOWERCASE_LETTER, Character.getType('u'));
}
@Test
public void givenACharacter_whenTitleCaseLetter_thenAssertTrue() {
assertTrue(Character.getType('\u01f2') == Character.TITLECASE_LETTER);
assertEquals(Character.TITLECASE_LETTER, Character.getType('\u01f2'));
}
@Test
public void givenACharacter_whenModifierLetter_thenAssertTrue() {
assertTrue(Character.getType('\u02b0') == Character.MODIFIER_LETTER);
assertEquals(Character.MODIFIER_LETTER, Character.getType('\u02b0'));
}
@Test
public void givenACharacter_whenOtherLetter_thenAssertTrue() {
assertTrue(Character.getType('\u05d0') == Character.OTHER_LETTER);
assertEquals(Character.OTHER_LETTER, Character.getType('\u05d0'));
}
@Test
public void givenACharacter_whenLetterNumber_thenAssertTrue() {
assertTrue(Character.getType('\u2164') == Character.LETTER_NUMBER);
assertEquals(Character.LETTER_NUMBER, Character.getType('\u2164'));
}
}

View File

@ -6,6 +6,27 @@ import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
public class IsLetterOrAlphabetUnitTest {
@Test
public void givenACharacter_whenUpperCaseLetter_thenAssertIsAlphabeticTrue() {
assertTrue(Character.isAlphabetic('A'));
}
@Test
public void givenACharacter_whenTitleCaseLetter_thenAssertIsAlphabeticTrue() {
assertTrue(Character.isAlphabetic('\u01f2'));
}
@Test
public void givenACharacter_whenLowerCaseLetter_thenAssertIsLetterTrue() {
assertTrue(Character.isAlphabetic('a'));
}
@Test
public void givenACharacter_whenModifierLetter_thenAssertIsLetterTrue() {
assertTrue(Character.isAlphabetic('\u02b0'));
}
@Test
public void givenACharacter_whenLetter_thenAssertIsLetterTrue() {
assertTrue(Character.isLetter('a'));

View File

@ -35,7 +35,7 @@
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.10</version>
<version>${commons-lang3.version}</version>
</dependency>
</dependencies>

View File

@ -0,0 +1,7 @@
=========
## Core Java Collections Cookbooks and Examples
### Relevant Articles:
- [ArrayList vs. LinkedList vs. HashMap in Java](https://www.baeldung.com/java-arraylist-vs-linkedlist-vs-hashmap)

View File

@ -0,0 +1,31 @@
<?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-collections-4</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-collections-4</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<assertj.version>3.18.0</assertj.version>
</properties>
</project>

View File

@ -0,0 +1,30 @@
package com.baeldung.collections.comparation;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class ArrayListUnitTest {
@Test
void givenArrayList_whenItemAddedToSpecificIndex_thenItCanBeRetrieved() {
List<String> list = new ArrayList<>();
list.add("Daniel");
list.add(0, "Marko");
assertThat(list).hasSize(2);
assertThat(list.get(0)).isEqualTo("Marko");
}
@Test
void givenArrayList_whenItemRemovedViaIndex_thenListSizeIsReduced() {
List<String> list = new ArrayList<>(Arrays.asList("Daniel", "Marko"));
list.remove(1);
assertThat(list).hasSize(1);
assertThat(list).doesNotContain("Marko");
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.collections.comparation;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
public class HashMapUnitTest {
@Test
void givenHashMap_whenItemAddedByKey_thenItCanBeRetrieved() {
Map<String, String> map = new HashMap<>();
map.put("123456", "Daniel");
map.put("654321", "Marko");
assertThat(map.get("654321")).isEqualTo("Marko");
}
@Test
void givenHashMap_whenItemRemovedByKey_thenMapSizeIsReduced() {
Map<String, String> map = new HashMap<>();
map.put("123456", "Daniel");
map.put("654321", "Marko");
map.remove("654321");
assertThat(map).hasSize(1);
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.collections.comparation;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class LinkedListUnitTest {
@Test
void givenLinkedList_whenItemIsAppended_thenItCanBeRetrieved() {
LinkedList<String> list = new LinkedList<>();
list.addLast("Daniel");
list.addFirst("Marko");
assertThat(list).hasSize(2);
assertThat(list.getLast()).isEqualTo("Daniel");
}
@Test
void givenLinkedList_whenItemIsRemoved_thenListSizeIsReduced() {
LinkedList<String> list = new LinkedList<>(Arrays.asList("Daniel", "Marko", "David"));
list.removeFirst();
list.removeLast();
assertThat(list).hasSize(1);
assertThat(list).containsExactly("Marko");
}
@Test
void givenLinkedList_whenItemInserted_thenItCanBeRetrievedAndDeleted() {
LinkedList<String> list = new LinkedList<>();
list.push("Daniel");
list.push("Marko");
assertThat(list.poll()).isEqualTo("Marko");
assertThat(list).hasSize(1);
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.collections.comparation;
import static org.assertj.core.api.Assertions.*;
import org.junit.jupiter.api.Test;
import java.util.*;
class ListVsMapUnitTest {
@Test
void givenList_whenIteratingTroughValues_thenEachValueIsPresent() {
List<String> list = new ArrayList<>();
list.add("Daniel");
list.add("Marko");
for (String name : list) {
assertThat(name).isIn(list);
}
assertThat(list).containsExactly("Daniel", "Marko");
}
@Test
void givenMap_whenIteratingTroughValues_thenEachValueIsPresent() {
Map<Integer, String> map = new HashMap<>();
map.put(1, "Daniel");
map.put(2, "Marko");
for (String name : map.values()) {
assertThat(name).isIn(map.values());
}
assertThat(map.values()).containsExactlyInAnyOrder("Daniel", "Marko");
}
}

View File

@ -36,7 +36,6 @@
<properties>
<commons-collections4.version>4.1</commons-collections4.version>
<commons-lang3.version>3.8.1</commons-lang3.version>
<assertj.version>3.11.1</assertj.version>
</properties>

View File

@ -26,7 +26,7 @@ public class Product {
return tags;
}
public Product addTagsOfOtherProdcut(Product product) {
public Product addTagsOfOtherProduct(Product product) {
this.tags.addAll(product.getTags());
return this;
}
@ -100,11 +100,11 @@ public class Product {
HashMap<String, Product> productsByName = new HashMap<>();
Product eBike2 = new Product("E-Bike", "A bike with a battery");
eBike2.getTags().add("sport");
productsByName.merge("E-Bike", eBike2, Product::addTagsOfOtherProdcut);
productsByName.merge("E-Bike", eBike2, Product::addTagsOfOtherProduct);
//Prior to Java 8:
if(productsByName.containsKey("E-Bike")) {
productsByName.get("E-Bike").addTagsOfOtherProdcut(eBike2);
productsByName.get("E-Bike").addTagsOfOtherProduct(eBike2);
} else {
productsByName.put("E-Bike", eBike2);
}
@ -117,7 +117,7 @@ public class Product {
productsByName.compute("E-Bike", (k,v) -> {
if(v != null) {
return v.addTagsOfOtherProdcut(eBike2);
return v.addTagsOfOtherProduct(eBike2);
} else {
return eBike2;
}
@ -125,7 +125,7 @@ public class Product {
//Prior to Java 8:
if(productsByName.containsKey("E-Bike")) {
productsByName.get("E-Bike").addTagsOfOtherProdcut(eBike2);
productsByName.get("E-Bike").addTagsOfOtherProduct(eBike2);
} else {
productsByName.put("E-Bike", eBike2);
}

View File

@ -6,4 +6,5 @@ This module contains articles about Map data structures in Java.
- [Java TreeMap vs HashMap](https://www.baeldung.com/java-treemap-vs-hashmap)
- [Comparing Two HashMaps in Java](https://www.baeldung.com/java-compare-hashmaps)
- [The Map.computeIfAbsent() Method](https://www.baeldung.com/java-map-computeifabsent)
- [Collections.synchronizedMap vs. ConcurrentHashMap](https://www.baeldung.com/java-synchronizedmap-vs-concurrenthashmap)
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-2)

View File

@ -15,7 +15,16 @@
</parent>
<dependencies>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
</dependencies>
<properties>

View File

@ -0,0 +1,96 @@
package com.baeldung.map.concurrenthashmap;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Threads;
import org.openjdk.jmh.annotations.Warmup;
@Fork(5)
@Threads(10)
@Warmup(iterations = 5)
@State(Scope.Benchmark)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class MapPerformanceComparison {
private int TEST_NO_ITEMS;
public static void main(String[] args) throws Exception {
org.openjdk.jmh.Main.main(args);
}
@Setup
public void setup() {
TEST_NO_ITEMS = 1000;
}
@Benchmark
public void randomReadAndWriteSynchronizedMap() {
Map<String, Integer> map = Collections.synchronizedMap(new HashMap<String, Integer>());
performReadAndWriteTest(map);
}
@Benchmark
public void randomReadAndWriteConcurrentHashMap() {
Map<String, Integer> map = new ConcurrentHashMap<>();
performReadAndWriteTest(map);
}
private void performReadAndWriteTest(final Map<String, Integer> map) {
for (int i = 0; i < TEST_NO_ITEMS; i++) {
Integer randNumber = (int) Math.ceil(Math.random() * TEST_NO_ITEMS);
map.get(String.valueOf(randNumber));
map.put(String.valueOf(randNumber), randNumber);
}
}
@Benchmark
public void randomWriteSynchronizedMap() {
Map<String, Integer> map = Collections.synchronizedMap(new HashMap<String, Integer>());
performWriteTest(map);
}
@Benchmark
public void randomWriteConcurrentHashMap() {
Map<String, Integer> map = new ConcurrentHashMap<>();
performWriteTest(map);
}
private void performWriteTest(final Map<String, Integer> map) {
for (int i = 0; i < TEST_NO_ITEMS; i++) {
Integer randNumber = (int) Math.ceil(Math.random() * TEST_NO_ITEMS);
map.put(String.valueOf(randNumber), randNumber);
}
}
@Benchmark
public void randomReadSynchronizedMap() {
Map<String, Integer> map = Collections.synchronizedMap(new HashMap<String, Integer>());
performReadTest(map);
}
@Benchmark
public void randomReadConcurrentHashMap() {
Map<String, Integer> map = new ConcurrentHashMap<>();
performReadTest(map);
}
private void performReadTest(final Map<String, Integer> map) {
for (int i = 0; i < TEST_NO_ITEMS; i++) {
Integer randNumber = (int) Math.ceil(Math.random() * TEST_NO_ITEMS);
map.get(String.valueOf(randNumber));
}
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.map.propertieshashmap;
import com.google.common.collect.Maps;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;
public class PropertiesToHashMapConverter {
@SuppressWarnings({"rawtypes", "unchecked"})
public static HashMap<String, String> typeCastConvert(Properties prop) {
Map step1 = prop;
Map<String, String> step2 = (Map<String, String>) step1;
return new HashMap<>(step2);
}
public static HashMap<String, String> loopConvert(Properties prop) {
HashMap<String, String> retMap = new HashMap<>();
for (Map.Entry<Object, Object> entry : prop.entrySet()) {
retMap.put(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
}
return retMap;
}
public static HashMap<String, String> streamConvert(Properties prop) {
return prop.entrySet().stream().collect(
Collectors.toMap(
e -> String.valueOf(e.getKey()),
e -> String.valueOf(e.getValue()),
(prev, next) -> next, HashMap::new
));
}
public static HashMap<String, String> guavaConvert(Properties prop) {
return Maps.newHashMap(Maps.fromProperties(prop));
}
}

View File

@ -0,0 +1,70 @@
package com.baeldung.map.concurrenthashmap;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import org.junit.Assert;
import org.junit.Test;
public class ConcurrentModificationErrorUnitTest {
@Test(expected = ConcurrentModificationException.class)
public void whenRemoveAndAddOnHashMap_thenConcurrentModificationError() {
Map<Integer, String> map = new HashMap<>();
map.put(1, "baeldung");
map.put(2, "HashMap");
Map<Integer, String> synchronizedMap = Collections.synchronizedMap(map);
Iterator<Entry<Integer, String>> iterator = synchronizedMap.entrySet().iterator();
while (iterator.hasNext()) {
synchronizedMap.put(3, "Modification");
iterator.next();
}
}
@Test(expected = ConcurrentModificationException.class)
public void whenRemoveAndAddOnTreeMap_thenConcurrentModificationError() {
Map<Integer, String> map = new TreeMap<>();
map.put(1, "baeldung");
map.put(2, "HashMap");
Map<Integer, String> synchronizedMap = Collections.synchronizedMap(map);
Iterator<Entry<Integer, String>> iterator = synchronizedMap.entrySet().iterator();
while (iterator.hasNext()) {
synchronizedMap.put(3, "Modification");
iterator.next();
}
}
@Test(expected = ConcurrentModificationException.class)
public void whenRemoveAndAddOnLinkedHashMap_thenConcurrentModificationError() {
Map<Integer, String> map = new LinkedHashMap<>();
map.put(1, "baeldung");
map.put(2, "HashMap");
Map<Integer, String> synchronizedMap = Collections.synchronizedMap(map);
Iterator<Entry<Integer, String>> iterator = synchronizedMap.entrySet().iterator();
while (iterator.hasNext()) {
synchronizedMap.put(3, "Modification");
iterator.next();
}
}
@Test
public void whenRemoveAndAddOnConcurrentHashMap_thenNoError() {
Map<Integer, String> map = new ConcurrentHashMap<>();
map.put(1, "baeldung");
map.put(2, "HashMap");
Iterator<Entry<Integer, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
map.put(3, "Modification");
iterator.next();
}
Assert.assertEquals(3, map.size());
}
}

View File

@ -0,0 +1,73 @@
package com.baeldung.map.concurrenthashmap;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import org.junit.Assert;
import org.junit.Test;
public class NullAllowInMapUnitTest {
@Test
public void givenHashMapBackedSynchronizedMap_whenNullAsKey_thenNoError() {
Map<String, Integer> map = Collections
.synchronizedMap(new HashMap<String, Integer>());
map.put(null, 1);
Assert.assertTrue(map.get(null).equals(1));
}
@Test(expected = NullPointerException.class)
public void givenTreeMapBackedSynchronizedMap_whenNullAsKey_thenException() {
Map<String, Integer> map = Collections.synchronizedMap(new TreeMap<String, Integer>());
map.put(null, 1);
Assert.assertTrue(map.get(null).equals(1));
}
@Test
public void givenLinkedHashMapBackedSynchronizedMap_whenNullAsKey_thenNoError() {
Map<String, Integer> map = Collections
.synchronizedMap(new LinkedHashMap<String, Integer>());
map.put(null, 1);
Assert.assertTrue(map.get(null).equals(1));
}
@Test(expected = NullPointerException.class)
public void givenConcurrentHasMap_whenNullAsKey_thenException() {
Map<String, Integer> map = new ConcurrentHashMap<>();
map.put(null, 1);
}
@Test
public void givenHashMapBackedSynchronizedMap_whenNullAsValue_thenNoError() {
Map<String, Integer> map = Collections.synchronizedMap(new HashMap<String, Integer>());
map.put("1", null);
Assert.assertNull(map.get("1"));
}
@Test
public void givenTreeMapBackedSynchronizedMap_whenNullAsValue_thenNoError() {
Map<String, Integer> map = Collections.synchronizedMap(new TreeMap<String, Integer>());
map.put("1", null);
Assert.assertNull(map.get("1"));
}
@Test
public void givenLinkedHashMapBackedSynchronizedMap_whenNullAsValue_thenNoError() {
Map<String, Integer> map = Collections
.synchronizedMap(new LinkedHashMap<String, Integer>());
map.put("1", null);
Assert.assertNull(map.get("1"));
}
@Test(expected = NullPointerException.class)
public void givenConcurrentHasMap_whenNullAsValue_thenException() {
Map<String, Integer> map = new ConcurrentHashMap<>();
map.put("1", null);
}
}

View File

@ -0,0 +1,49 @@
package com.baeldung.map.hashmap.loadfactor;
import java.util.HashMap;
import java.util.Map;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
public class HashMapLoadFactorUnitTest {
@Test
public void whenCreateMapWithDefaultParam_thenSucces() {
Map<String, String> mapWithDefaultParams = new HashMap<>();
mapWithDefaultParams.put("1", "one");
mapWithDefaultParams.put("2", "two");
mapWithDefaultParams.put("3", "three");
mapWithDefaultParams.put("4", "four");
mapWithDefaultParams.put("5", "five");
Assert.assertEquals(5, mapWithDefaultParams.size());
}
@Test
public void whenCreateMapWithInitialCapacity_thenSucces() {
Map<String, String> mapWithInitialCapacity = new HashMap<>(5);
mapWithInitialCapacity.put("1", "one");
mapWithInitialCapacity.put("2", "two");
mapWithInitialCapacity.put("3", "three");
Assert.assertEquals(3, mapWithInitialCapacity.size());
}
@Test
public void whenCreateMapWithInitialCapacityAndLF_thenSucces() {
Map<String, String> mapWithInitialCapacityAndLF = new HashMap<>(5, 0.5f);
mapWithInitialCapacityAndLF.put("1", "one");
mapWithInitialCapacityAndLF.put("2", "two");
mapWithInitialCapacityAndLF.put("3", "three");
mapWithInitialCapacityAndLF.put("4", "four");
mapWithInitialCapacityAndLF.put("5", "five");
mapWithInitialCapacityAndLF.put("6", "six");
mapWithInitialCapacityAndLF.put("7", "seven");
mapWithInitialCapacityAndLF.put("8", "eight");
mapWithInitialCapacityAndLF.put("9", "nine");
mapWithInitialCapacityAndLF.put("10", "ten");
Assert.assertEquals(10, mapWithInitialCapacityAndLF.size());
}
}

View File

@ -0,0 +1,192 @@
package com.baeldung.map.propertieshashmap;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Properties;
import static org.junit.jupiter.api.Assertions.*;
class PropertiesToHashMapConverterUnitTest {
private Properties properties;
private final static String propertyFileName = "toHashMap.properties";
@BeforeEach
public void setup() throws IOException {
properties = new Properties();
try (InputStream is = getClass().getClassLoader().getResourceAsStream(propertyFileName)) {
if (is != null) {
properties.load(is);
}
}
}
@Test
public void havingPropertiesLoaded_whenCheck_thenEquals() {
assertEquals(3, properties.size());
assertEquals("str_value", properties.get("property1"));
assertEquals("123", properties.get("property2"));
assertEquals("", properties.get("property3"));
}
@Test
public void whenPropertiesModified_thenTypeSafeIssues() {
compromiseProperties(properties);
assertEquals(5, properties.size());
assertNull(properties.getProperty("property4"));
assertNotEquals(String.class, properties.get("property4").getClass());
assertEquals(456, properties.get("property4"));
assertNull(properties.getProperty("5"));
assertNotEquals(String.class, properties.get(5).getClass());
assertEquals(10.11, properties.get(5));
}
@Test
public void havingNonModifiedProperties_whenTypeCastConvert_thenNoTypeSafeIssues() {
HashMap<String, String> hMap = PropertiesToHashMapConverter.typeCastConvert(properties);
assertEquals(3, hMap.size());
assertEquals(String.class, hMap.get("property1").getClass());
assertEquals(properties.get("property1"), hMap.get("property1"));
assertEquals(String.class, hMap.get("property2").getClass());
assertEquals(properties.get("property2"), hMap.get("property2"));
assertEquals(String.class, hMap.get("property3").getClass());
assertEquals(properties.get("property3"), hMap.get("property3"));
}
@Test
public void havingModifiedProperties_whenTypeCastConvert_thenClassCastException() {
compromiseProperties(properties);
HashMap<String, String> hMap = PropertiesToHashMapConverter.typeCastConvert(properties);
assertEquals(5, hMap.size());
assertThrows(ClassCastException.class, () -> {
String s = hMap.get("property4");
});
assertEquals(Integer.class, ((Object) hMap.get("property4")).getClass());
assertNull(hMap.get("5"));
assertNotNull(hMap.get(5));
assertThrows(ClassCastException.class, () -> {
String s = hMap.get(5);
});
assertEquals(Double.class, ((Object) hMap.get(5)).getClass());
}
@Test
public void havingNonModifiedProperties_whenLoopConvert_thenNoTypeSafeIssues() {
HashMap<String, String> hMap = PropertiesToHashMapConverter.loopConvert(properties);
assertEquals(3, hMap.size());
assertEquals(String.class, hMap.get("property1").getClass());
assertEquals(properties.get("property1"), hMap.get("property1"));
assertEquals(String.class, hMap.get("property2").getClass());
assertEquals(properties.get("property2"), hMap.get("property2"));
assertEquals(String.class, hMap.get("property3").getClass());
assertEquals(properties.get("property3"), hMap.get("property3"));
}
@Test
public void havingModifiedProperties_whenLoopConvert_thenNoClassCastException() {
compromiseProperties(properties);
HashMap<String, String> hMap = PropertiesToHashMapConverter.loopConvert(properties);
assertEquals(5, hMap.size());
assertDoesNotThrow(() -> {
String s = hMap.get("property4");
});
assertEquals(String.class, hMap.get("property4").getClass());
assertEquals("456", hMap.get("property4"));
assertDoesNotThrow(() -> {
String s = hMap.get("5");
});
assertEquals("10.11", hMap.get("5"));
}
@Test
public void havingNonModifiedProperties_whenStreamConvert_thenNoTypeSafeIssues() {
HashMap<String, String> hMap = PropertiesToHashMapConverter.streamConvert(properties);
assertEquals(3, hMap.size());
assertEquals(String.class, hMap.get("property1").getClass());
assertEquals(properties.get("property1"), hMap.get("property1"));
assertEquals(String.class, hMap.get("property2").getClass());
assertEquals(properties.get("property2"), hMap.get("property2"));
assertEquals(String.class, hMap.get("property3").getClass());
assertEquals(properties.get("property3"), hMap.get("property3"));
}
@Test
public void havingModifiedProperties_whenStreamConvert_thenNoClassCastException() {
compromiseProperties(properties);
HashMap<String, String> hMap = PropertiesToHashMapConverter.streamConvert(properties);
assertEquals(5, hMap.size());
assertDoesNotThrow(() -> {
String s = hMap.get("property4");
});
assertEquals(String.class, hMap.get("property4").getClass());
assertEquals("456", hMap.get("property4"));
assertDoesNotThrow(() -> {
String s = hMap.get("5");
});
assertEquals("10.11", hMap.get("5"));
}
@Test
public void havingModifiedProperties_whenLoopConvertAndStreamConvert_thenHashMapsSame() {
compromiseProperties(properties);
HashMap<String, String> hMap1 = PropertiesToHashMapConverter.loopConvert(properties);
HashMap<String, String> hMap2 = PropertiesToHashMapConverter.streamConvert(properties);
assertEquals(hMap2, hMap1);
}
@Test
public void havingNonModifiedProperties_whenGuavaConvert_thenNoTypeSafeIssues() {
HashMap<String, String> hMap = PropertiesToHashMapConverter.guavaConvert(properties);
assertEquals(3, hMap.size());
assertEquals(String.class, hMap.get("property1").getClass());
assertEquals(properties.get("property1"), hMap.get("property1"));
assertEquals(String.class, hMap.get("property2").getClass());
assertEquals(properties.get("property2"), hMap.get("property2"));
assertEquals(String.class, hMap.get("property3").getClass());
assertEquals(properties.get("property3"), hMap.get("property3"));
}
@Test
public void havingModifiedProperties_whenGuavaConvert_thenUnableToConvertAndThrowException() {
compromiseProperties(properties);
assertThrows(Exception.class, () -> PropertiesToHashMapConverter.guavaConvert(properties));
}
@Test
public void havingModifiedPropertiesWithNoIntegerValue_whenGuavaConvert_thenNullPointerException() {
properties.put("property4", 456);
assertThrows(NullPointerException.class, () -> PropertiesToHashMapConverter.guavaConvert(properties));
}
@Test
public void havingModifiedPropertiesWithNoIntegerKey_whenGuavaConvert_thenClassCastException() {
properties.put(5, 10.11);
assertThrows(ClassCastException.class, () -> PropertiesToHashMapConverter.guavaConvert(properties));
}
private void compromiseProperties(Properties prop) {
prop.put("property4", 456);
prop.put(5, 10.11);
}
}

View File

@ -0,0 +1,3 @@
property1=str_value
property2=123
property3=

View File

@ -10,11 +10,17 @@ import org.openjdk.jcstress.annotations.Outcome;
import org.openjdk.jcstress.annotations.State;
import org.openjdk.jcstress.infra.results.I_Result;
/**
* This is defined as a manual test because it tries to simulate the race conditions
* in a concurrent program that is poorly designed and hence may fail nondeterministically.
* This will help the CI jobs to ignore these tests and a developer to run them manually.
*
*/
@JCStressTest
@Outcome(id = "1", expect = ACCEPTABLE_INTERESTING, desc = "One update lost.")
@Outcome(id = "2", expect = ACCEPTABLE, desc = "Both updates.")
@State
public class MyCounterJCStressUnitTest {
public class MyCounterJCStressManualTest {
private MyCounter counter;

View File

@ -1,12 +1,17 @@
package com.baeldung.concurrent;
import org.junit.Ignore;
import org.junit.Test;
import edu.umd.cs.mtc.MultithreadedTestCase;
import edu.umd.cs.mtc.TestFramework;
public class MyCounterMultithreadedTCUnitTest extends MultithreadedTestCase {
/**
* This is defined as a manual test because it tries to simulate the race conditions
* in a concurrent program that is poorly designed and hence may fail nondeterministically.
* This will help the CI jobs to ignore these tests and a developer to run them manually.
*
*/
public class MyCounterMultithreadedTCManualTest extends MultithreadedTestCase {
private MyCounter counter;
@ -29,9 +34,8 @@ public class MyCounterMultithreadedTCUnitTest extends MultithreadedTestCase {
assertEquals(2, counter.getCount());
}
@Ignore
@Test
public void testCounter() throws Throwable {
TestFramework.runManyTimes(new MyCounterMultithreadedTCUnitTest(), 1000);
TestFramework.runManyTimes(new MyCounterMultithreadedTCManualTest(), 1000);
}
}

View File

@ -0,0 +1,63 @@
package com.baeldung.concurrent;
import static org.junit.Assert.assertEquals;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.junit.Test;
/**
* This is defined as a manual test because it tries to simulate the race conditions
* in a concurrent program that is poorly designed and hence may fail nondeterministically.
* This will help the CI jobs to ignore these tests and a developer to run them manually.
*
*/
public class MyCounterSimpleManualTest {
@Test
public void testCounter() {
MyCounter counter = new MyCounter();
for (int i = 0; i < 500; i++)
counter.increment();
assertEquals(500, counter.getCount());
}
@Test
public void testCounterWithConcurrency() throws InterruptedException {
int numberOfThreads = 100;
ExecutorService service = Executors.newFixedThreadPool(10);
CountDownLatch latch = new CountDownLatch(numberOfThreads);
MyCounter counter = new MyCounter();
for (int i = 0; i < numberOfThreads; i++) {
service.execute(() -> {
counter.increment();
latch.countDown();
});
}
latch.await();
assertEquals(numberOfThreads, counter.getCount());
}
@Test
public void testSummationWithConcurrencyAndWait() throws InterruptedException {
int numberOfThreads = 2;
ExecutorService service = Executors.newFixedThreadPool(10);
CountDownLatch latch = new CountDownLatch(numberOfThreads);
MyCounter counter = new MyCounter();
for (int i = 0; i < numberOfThreads; i++) {
service.submit(() -> {
try {
counter.incrementWithWait();
} catch (InterruptedException e) {
e.printStackTrace();
}
latch.countDown();
});
}
latch.await();
assertEquals(numberOfThreads, counter.getCount());
}
}

View File

@ -1,60 +0,0 @@
package com.baeldung.concurrent;
import static org.junit.Assert.assertEquals;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.junit.Ignore;
import org.junit.Test;
public class MyCounterSimpleUnitTest {
@Test
public void testCounter() {
MyCounter counter = new MyCounter();
for (int i = 0; i < 500; i++)
counter.increment();
assertEquals(500, counter.getCount());
}
@Ignore
@Test
public void testCounterWithConcurrency() throws InterruptedException {
int numberOfThreads = 100;
ExecutorService service = Executors.newFixedThreadPool(10);
CountDownLatch latch = new CountDownLatch(numberOfThreads);
MyCounter counter = new MyCounter();
for (int i = 0; i < numberOfThreads; i++) {
service.execute(() -> {
counter.increment();
latch.countDown();
});
}
latch.await();
assertEquals(numberOfThreads, counter.getCount());
}
@Ignore
@Test
public void testSummationWithConcurrencyAndWait() throws InterruptedException {
int numberOfThreads = 2;
ExecutorService service = Executors.newFixedThreadPool(10);
CountDownLatch latch = new CountDownLatch(numberOfThreads);
MyCounter counter = new MyCounter();
for (int i = 0; i < numberOfThreads; i++) {
service.submit(() -> {
try {
counter.incrementWithWait();
} catch (InterruptedException e) {
e.printStackTrace();
}
latch.countDown();
});
}
latch.await();
assertEquals(numberOfThreads, counter.getCount());
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.concurrent;
import static org.junit.Assert.assertEquals;
import org.junit.AfterClass;
import org.junit.Rule;
import org.junit.Test;
import com.google.code.tempusfugit.concurrency.ConcurrentRule;
import com.google.code.tempusfugit.concurrency.RepeatingRule;
import com.google.code.tempusfugit.concurrency.annotations.Concurrent;
import com.google.code.tempusfugit.concurrency.annotations.Repeating;
/**
* This is defined as a manual test because it tries to simulate the race conditions
* in a concurrent program that is poorly designed and hence may fail nondeterministically.
* This will help the CI jobs to ignore these tests and a developer to run them manually.
*
*/
public class MyCounterTempusFugitManualTest {
@Rule
public ConcurrentRule concurrently = new ConcurrentRule();
@Rule
public RepeatingRule rule = new RepeatingRule();
private static MyCounter counter = new MyCounter();
@Test
@Concurrent(count = 2)
@Repeating(repetition = 10)
public void runsMultipleTimes() {
counter.increment();
}
@AfterClass
public static void annotatedTestRunsMultipleTimes() throws InterruptedException {
assertEquals(counter.getCount(), 20);
}
}

View File

@ -1,37 +0,0 @@
package com.baeldung.concurrent;
import static org.junit.Assert.assertEquals;
import org.junit.AfterClass;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import com.google.code.tempusfugit.concurrency.ConcurrentRule;
import com.google.code.tempusfugit.concurrency.RepeatingRule;
import com.google.code.tempusfugit.concurrency.annotations.Concurrent;
import com.google.code.tempusfugit.concurrency.annotations.Repeating;
public class MyCounterTempusFugitUnitTest {
@Rule
public ConcurrentRule concurrently = new ConcurrentRule();
@Rule
public RepeatingRule rule = new RepeatingRule();
private static MyCounter counter = new MyCounter();
@Ignore
@Test
@Concurrent(count = 2)
@Repeating(repetition = 10)
public void runsMultipleTimes() {
counter.increment();
}
@AfterClass
public static void annotatedTestRunsMultipleTimes() throws InterruptedException {
assertEquals(counter.getCount(), 20);
}
}

View File

@ -0,0 +1,48 @@
package com.baeldung.concurrent;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.google.testing.threadtester.AnnotatedTestRunner;
import com.google.testing.threadtester.ThreadedAfter;
import com.google.testing.threadtester.ThreadedBefore;
import com.google.testing.threadtester.ThreadedMain;
import com.google.testing.threadtester.ThreadedSecondary;
/**
* This is defined as a manual test because it tries to simulate the race conditions
* in a concurrent program that is poorly designed and hence may fail nondeterministically.
* This will help the CI jobs to ignore these tests and a developer to run them manually.
*
*/
public class MyCounterThreadWeaverManualTest {
private MyCounter counter;
@ThreadedBefore
public void before() {
counter = new MyCounter();
}
@ThreadedMain
public void mainThread() {
counter.increment();
}
@ThreadedSecondary
public void secondThread() {
counter.increment();
}
@ThreadedAfter
public void after() {
assertEquals(2, counter.getCount());
}
@Test
public void testCounter() {
new AnnotatedTestRunner().runTests(this.getClass(), MyCounter.class);
}
}

View File

@ -1,44 +0,0 @@
package com.baeldung.concurrent;
import static org.junit.Assert.assertEquals;
import org.junit.Ignore;
import org.junit.Test;
import com.google.testing.threadtester.AnnotatedTestRunner;
import com.google.testing.threadtester.ThreadedAfter;
import com.google.testing.threadtester.ThreadedBefore;
import com.google.testing.threadtester.ThreadedMain;
import com.google.testing.threadtester.ThreadedSecondary;
public class MyCounterThreadWeaverUnitTest {
private MyCounter counter;
@ThreadedBefore
public void before() {
counter = new MyCounter();
}
@ThreadedMain
public void mainThread() {
counter.increment();
}
@ThreadedSecondary
public void secondThread() {
counter.increment();
}
@ThreadedAfter
public void after() {
assertEquals(2, counter.getCount());
}
@Ignore
@Test
public void testCounter() {
new AnnotatedTestRunner().runTests(this.getClass(), MyCounter.class);
}
}

View File

@ -0,0 +1,4 @@
### Relevant Articles:
- [Binary Semaphore vs Reentrant Lock](https://www.baeldung.com/java-binary-semaphore-vs-reentrant-lock)
- [Bad Practices With Synchronization](https://www.baeldung.com/java-synchronization-bad-practices)

View File

@ -0,0 +1,47 @@
<?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-concurrency-advanced-4</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-concurrency-advanced-4</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent>
<dependencies>
</dependencies>
<build>
<finalName>core-java-concurrency-advanced-4</finalName>
<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>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
</project>

View File

@ -0,0 +1,35 @@
package com.baeldung.synchronizationbadpractices;
public class AnimalBadPractice {
private String name;
private String owner;
public String getName() {
return name;
}
public String getOwner() {
return owner;
}
public synchronized void setName(String name) {
this.name = name;
}
public void setOwner(String owner) {
synchronized(this) {
this.owner = owner;
}
}
public AnimalBadPractice() {
}
public AnimalBadPractice(String name, String owner) {
this.name = name;
this.owner = owner;
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.synchronizationbadpractices;
public class AnimalSolution {
private final Object objLock1 = new Object();
private final Object objLock2 = new Object();
private String name;
private String owner;
public String getName() {
return name;
}
public String getOwner() {
return owner;
}
public void setName(String name) {
synchronized(objLock1) {
this.name = name;
}
}
public void setOwner(String owner) {
synchronized(objLock2) {
this.owner = owner;
}
}
public AnimalSolution() {
}
public AnimalSolution(String name, String owner) {
this.name = name;
this.owner = owner;
}
}

View File

@ -0,0 +1,51 @@
package com.baeldung.synchronizationbadpractices;
public class SynchronizationBadPracticeExample {
public void stringBadPractice1() {
String stringLock = "LOCK_STRING";
synchronized (stringLock) {
// ...
}
}
private final String stringLock = "LOCK_STRING";
public void stringBadPractice2() {
synchronized (stringLock) {
// ...
}
}
private final String internedStringLock = new String("LOCK_STRING").intern();
public void stringBadPractice3() {
synchronized (internedStringLock) {
// ...
}
}
private final Boolean booleanLock = Boolean.FALSE;
public void booleanBadPractice() {
synchronized (booleanLock) {
// ...
}
}
private int count = 0;
private final Integer intLock = count;
public void boxedPrimitiveBadPractice() {
synchronized (intLock) {
count++;
// ...
}
}
public void classBadPractice() throws InterruptedException {
AnimalBadPractice animalObj = new AnimalBadPractice("Tommy", "John");
synchronized(animalObj) {
while (true) {
Thread.sleep(Integer.MAX_VALUE);
}
}
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.synchronizationbadpractices;
public class SynchronizationSolutionExample {
private final String stringLock = new String("LOCK_STRING");
public void stringSolution() {
synchronized (stringLock) {
// ...
}
}
private int count = 0;
private final Integer intLock = new Integer(count);
public void boxedPrimitiveSolution() {
synchronized(intLock) {
count++;
// ...
}
}
private static int staticCount = 0;
private static final Object staticObjLock = new Object();
public void staticVariableSolution() {
synchronized(staticObjLock) {
staticCount++;
// ...
}
}
}

View File

@ -0,0 +1,58 @@
package com.baeldung.binarysemaphorereentrantlock;
import static org.junit.Assert.assertEquals;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.ReentrantLock;
import org.junit.Test;
public class BinarySemaphoreVsReentrantLockUnitTest {
@Test
public void givenBinarySemaphore_whenAcquireAndRelease_thenCheckAvailablePermits() throws InterruptedException {
Semaphore binarySemaphore = new Semaphore(1);
try {
binarySemaphore.acquire();
assertEquals(0, binarySemaphore.availablePermits());
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
binarySemaphore.release();
assertEquals(1, binarySemaphore.availablePermits());
}
}
@Test
public void givenReentrantLock_whenLockAndUnlock_thenCheckHoldCountAndIsLocked() throws InterruptedException {
ReentrantLock reentrantLock = new ReentrantLock();
try {
reentrantLock.lock();
assertEquals(1, reentrantLock.getHoldCount());
assertEquals(true, reentrantLock.isLocked());
} finally {
reentrantLock.unlock();
assertEquals(0, reentrantLock.getHoldCount());
assertEquals(false, reentrantLock.isLocked());
}
}
@Test
public void givenReentrantLock_whenLockMultipleTimes_thenUnlockMultipleTimesToRelease() throws InterruptedException {
ReentrantLock reentrantLock = new ReentrantLock();
try {
reentrantLock.lock();
reentrantLock.lock();
assertEquals(2, reentrantLock.getHoldCount());
assertEquals(true, reentrantLock.isLocked());
} finally {
reentrantLock.unlock();
assertEquals(1, reentrantLock.getHoldCount());
assertEquals(true, reentrantLock.isLocked());
reentrantLock.unlock();
assertEquals(0, reentrantLock.getHoldCount());
assertEquals(false, reentrantLock.isLocked());
}
}
}

View File

@ -6,6 +6,7 @@ import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.util.TimeZone;
import static org.assertj.core.api.Assertions.assertThat;
@ -21,9 +22,12 @@ public class ConvertInstantToTimestampUnitTest {
instant = timestamp.toInstant();
assertThat(instant.toEpochMilli()).isEqualTo(timestamp.getTime());
DateFormat df = DateFormat.getDateTimeInstance();
df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS'Z'");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
formatter = formatter.withZone(TimeZone.getTimeZone("UTC").toZoneId());
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
assertThat(instant.toString()).isEqualTo(df.format(timestamp).toString());
assertThat(formatter.format(instant)).isEqualTo(df.format(timestamp));
}
}

View File

@ -58,7 +58,8 @@ public class StringToDateUnitTest {
LocalDateTime localDateTime = LocalDateTime.of(2015, 05, 05, 10, 15, 30);
ZonedDateTime expectedZonedDateTime = ZonedDateTime.of(localDateTime, ZoneId.of("Europe/Paris"));
ZonedDateTime zonedDateTime = ZonedDateTime.parse("2015-05-05T10:15:30+01:00[Europe/Paris]");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z");
ZonedDateTime zonedDateTime = ZonedDateTime.parse("2015-05-05 10:15:30 Europe/Paris", formatter);
assertThat(zonedDateTime).isEqualTo(expectedZonedDateTime);
}

View File

@ -38,14 +38,16 @@ public class DateTimeFormatterUnitTest {
LocalDateTime localDateTime = LocalDateTime.of(2018, 1, 1, 10, 15, 50, 500);
ZoneId losAngelesTimeZone = TimeZone.getTimeZone("America/Los_Angeles").toZoneId();
DateTimeFormatter localizedFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL);
DateTimeFormatter frLocalizedFormatter =
DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).withLocale(Locale.FRANCE);
DateTimeFormatter localizedFormatter = DateTimeFormatter.ofPattern("EEEE, MMMM dd, yyyy z", Locale.US);
DateTimeFormatter frLocalizedFormatter = DateTimeFormatter.ofPattern("EEEE, MMMM dd, yyyy z", Locale.FRANCE);
String formattedDateTime = localizedFormatter.format(ZonedDateTime.of(localDateTime, losAngelesTimeZone));
String frFormattedDateTime = frLocalizedFormatter.format(ZonedDateTime.of(localDateTime, losAngelesTimeZone));
Assert.assertEquals("Monday, January 1, 2018 10:15:50 AM PST", formattedDateTime);
Assert.assertEquals("lundi 1 janvier 2018 10 h 15 PST", frFormattedDateTime);
System.out.println(formattedDateTime);
System.out.println(frFormattedDateTime);
Assert.assertEquals("Monday, January 01, 2018 PST", formattedDateTime);
Assert.assertEquals("lundi, janvier 01, 2018 PST", frFormattedDateTime);
}
@Test
@ -105,14 +107,15 @@ public class DateTimeFormatterUnitTest {
Assert.assertEquals("8/23/16", DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT).format(anotherSummerDay));
}
@Test
public void shouldPrintStyledDateTime() {
LocalDateTime anotherSummerDay = LocalDateTime.of(2016, 8, 23, 13, 12, 45);
Assert.assertEquals("Tuesday, August 23, 2016 1:12:45 PM EET", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay));
Assert.assertEquals("August 23, 2016 1:12:45 PM EET", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay));
Assert.assertEquals("Aug 23, 2016 1:12:45 PM", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay));
Assert.assertEquals("8/23/16 1:12 PM", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay));
}
// Note: The exact output format using the different FormatStyle constants differs by JVM/Java version
// @Test
// public void shouldPrintStyledDateTime() {
// LocalDateTime anotherSummerDay = LocalDateTime.of(2016, 8, 23, 13, 12, 45);
// Assert.assertEquals("Tuesday, August 23, 2016 1:12:45 PM EET", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay));
// Assert.assertEquals("August 23, 2016 1:12:45 PM EET", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay));
// Assert.assertEquals("Aug 23, 2016 1:12:45 PM", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay));
// Assert.assertEquals("8/23/16 1:12 PM", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay));
// }
@Test
public void shouldPrintFormattedDateTimeWithPredefined() {
@ -126,11 +129,12 @@ public class DateTimeFormatterUnitTest {
Assert.assertEquals(LocalDate.of(2018, 3, 12), LocalDate.from(DateTimeFormatter.ISO_LOCAL_DATE.parse("2018-03-09")).plusDays(3));
}
@Test
public void shouldParseFormatStyleFull() {
ZonedDateTime dateTime = ZonedDateTime.from(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).parse("Tuesday, August 23, 2016 1:12:45 PM EET"));
Assert.assertEquals(ZonedDateTime.of(LocalDateTime.of(2016, 8, 23, 22, 12, 45), ZoneId.of("Europe/Bucharest")), dateTime.plusHours(9));
}
// Note: The exact output format using the different FormatStyle constants differs by JVM/Java version
// @Test
// public void shouldParseFormatStyleFull() {
// ZonedDateTime dateTime = ZonedDateTime.from(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).parse("Tuesday, August 23, 2016 1:12:45 PM EET"));
// Assert.assertEquals(ZonedDateTime.of(LocalDateTime.of(2016, 8, 23, 22, 12, 45), ZoneId.of("Europe/Bucharest")), dateTime.plusHours(9));
// }
@Test
public void shouldParseDateWithCustomFormatter() {

View File

@ -7,3 +7,4 @@
- [Java IndexOutOfBoundsException “Source Does Not Fit in Dest”](https://www.baeldung.com/java-indexoutofboundsexception)
- [Localizing Exception Messages in Java](https://www.baeldung.com/java-localize-exception-messages)
- [Explanation of ClassCastException in Java](https://www.baeldung.com/java-classcastexception)
- [NoSuchFieldError in Java](https://www.baeldung.com/java-nosuchfielderror)

View File

@ -20,6 +20,8 @@ public class IllegalMonitorStateExceptionUnitTest {
senderThread.join(1000);
receiverThread.join(1000);
Thread.sleep(2000);
assertEquals("test", receiver.getMessage());
assertFalse(sender.hasIllegalMonitorStateExceptionOccurred());

View File

@ -24,9 +24,20 @@ public class ListFiles {
.collect(Collectors.toSet());
}
public Set<String> listFilesUsingFilesList(String dir) throws IOException {
try (Stream<Path> stream = Files.list(Paths.get(dir))) {
return stream
.filter(file -> !Files.isDirectory(file))
.map(Path::getFileName)
.map(Path::toString)
.collect(Collectors.toSet());
}
}
public Set<String> listFilesUsingFileWalk(String dir, int depth) throws IOException {
try (Stream<Path> stream = Files.walk(Paths.get(dir), depth)) {
return stream.filter(file -> !Files.isDirectory(file))
return stream
.filter(file -> !Files.isDirectory(file))
.map(Path::getFileName)
.map(Path::toString)
.collect(Collectors.toSet());

View File

@ -25,10 +25,15 @@ public class ListFilesUnitTest {
};
@Test
public void givenDir_whenUsingJAVAIO_thenListAllFiles() throws IOException {
public void givenDir_whenUsingJAVAIO_thenListAllFiles() {
assertEquals(EXPECTED_FILE_LIST, listFiles.listFilesUsingJavaIO(DIRECTORY));
}
@Test
public void givenDir_whenUsingFilesList_thenListAllFiles() throws IOException {
assertEquals(EXPECTED_FILE_LIST, listFiles.listFilesUsingFilesList(DIRECTORY));
}
@Test
public void givenDir_whenWalkingTree_thenListAllFiles() throws IOException {
assertEquals(EXPECTED_FILE_LIST, listFiles.listFilesUsingFileWalk(DIRECTORY,DEPTH));

View File

@ -12,4 +12,6 @@ This module contains articles about core Java input and output (IO)
- [Creating Temporary Directories in Java](https://www.baeldung.com/java-temp-directories)
- [Reading a Line at a Given Line Number From a File in Java](https://www.baeldung.com/java-read-line-at-number)
- [Find the Last Modified File in a Directory with Java](https://www.baeldung.com/java-last-modified-file)
- [Get a Filename Without the Extension in Java](https://www.baeldung.com/java-filename-without-extension)
- [Writing byte[] to a File in Java](https://www.baeldung.com/java-write-byte-array-file)
- [[<-- Prev]](/core-java-modules/core-java-io-2)

View File

@ -0,0 +1,14 @@
package com.baeldung.filenamewithoutextension;
public class MyFilenameUtil {
private MyFilenameUtil() {}
public static String removeFileExtension(String filename, boolean removeAllExtensions) {
if (filename == null || filename.isEmpty()) {
return filename;
}
String extPattern = "(?<!^)[.]" + (removeAllExtensions ? ".*" : "[^.]*$");
return filename.replaceAll(extPattern, "");
}
}

View File

@ -0,0 +1,72 @@
package com.baeldung.filenamewithoutextension;
import com.google.common.io.Files;
import org.apache.commons.io.FilenameUtils;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
public class FileNameDelExtensionUnitTest {
@Test
public void givenDotFileWithoutExt_whenCallGuavaMethod_thenCannotGetDesiredResult() {
//negative assertion
assertNotEquals(".baeldung", Files.getNameWithoutExtension(".baeldung"));
}
@Test
public void givenFileWithoutMultipleExt_whenCallGuavaMethod_thenCannotRemoveAllExtensions() {
//negative assertion
assertNotEquals("baeldung", Files.getNameWithoutExtension("baeldung.tar.gz"));
}
@Test
public void givenDotFileWithoutExt_whenCallApacheCommonsMethod_thenCannotGetDesiredResult() {
//negative assertion
assertNotEquals(".baeldung", FilenameUtils.removeExtension(".baeldung"));
}
@Test
public void givenFileWithoutMultipleExt_whenCallApacheCommonsMethod_thenCannotRemoveAllExtensions() {
//negative assertion
assertNotEquals("baeldung", FilenameUtils.removeExtension("baeldung.tar.gz"));
}
@Test
public void givenFilenameNoExt_whenCallFilenameUtilMethod_thenGetExpectedFilename() {
assertEquals("baeldung", MyFilenameUtil.removeFileExtension("baeldung", true));
assertEquals("baeldung", MyFilenameUtil.removeFileExtension("baeldung", false));
}
@Test
public void givenSingleExt_whenCallFilenameUtilMethod_thenGetExpectedFilename() {
assertEquals("baeldung", MyFilenameUtil.removeFileExtension("baeldung.txt", true));
assertEquals("baeldung", MyFilenameUtil.removeFileExtension("baeldung.txt", false));
}
@Test
public void givenDotFile_whenCallFilenameUtilMethod_thenGetExpectedFilename() {
assertEquals(".baeldung", MyFilenameUtil.removeFileExtension(".baeldung", true));
assertEquals(".baeldung", MyFilenameUtil.removeFileExtension(".baeldung", false));
}
@Test
public void givenDotFileWithExt_whenCallFilenameUtilMethod_thenGetExpectedFilename() {
assertEquals(".baeldung", MyFilenameUtil.removeFileExtension(".baeldung.conf", true));
assertEquals(".baeldung", MyFilenameUtil.removeFileExtension(".baeldung.conf", false));
}
@Test
public void givenDoubleExt_whenCallFilenameUtilMethod_thenGetExpectedFilename() {
assertEquals("baeldung", MyFilenameUtil.removeFileExtension("baeldung.tar.gz", true));
assertEquals("baeldung.tar", MyFilenameUtil.removeFileExtension("baeldung.tar.gz", false));
}
@Test
public void givenDotFileWithDoubleExt_whenCallFilenameUtilMethod_thenGetExpectedFilename() {
assertEquals(".baeldung", MyFilenameUtil.removeFileExtension(".baeldung.conf.bak", true));
assertEquals(".baeldung.conf", MyFilenameUtil.removeFileExtension(".baeldung.conf.bak", false));
}
}

View File

@ -0,0 +1,77 @@
package com.baeldung.writebytearray;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import org.apache.commons.io.FileUtils;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.google.common.io.ByteSink;
import com.google.common.io.MoreFiles;
public class WriteByteArrayUnitTest {
private static byte[] dataForWriting;
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
@BeforeClass
public static void setup() throws IOException {
dataForWriting = Files.readAllBytes(Paths.get("src/test/resources/example-image.jpg"));
}
@Test
public void whenUsingFileOutputStream_thenByteArrayIsWritten() throws IOException {
File outputFile = tempFolder.newFile("example-fos.jpg");
try (FileOutputStream outputStream = new FileOutputStream(outputFile)) {
outputStream.write(dataForWriting);
assertThat(outputFile).hasBinaryContent(dataForWriting);
}
}
@Test
public void whenUsingNioFiles_thenByteArrayIsWritten() throws IOException {
File outputFile = tempFolder.newFile("example-nio-files.jpg");
Files.write(outputFile.toPath(), dataForWriting);
assertThat(outputFile).hasBinaryContent(dataForWriting);
}
@Test
public void whenUsingGuavaFiles_thenByteArrayIsWritten() throws IOException {
File outputFile = tempFolder.newFile("example-guava-files.jpg");
com.google.common.io.Files.write(dataForWriting, outputFile);
assertThat(outputFile).hasBinaryContent(dataForWriting);
}
@Test
public void whenUsingGuavaByteSink_thenByteArrayIsWritten() throws IOException {
File outputFile = tempFolder.newFile("example-guava-bs.jpg");
ByteSink byteSink = com.google.common.io.Files.asByteSink(outputFile);
byteSink.write(dataForWriting);
assertThat(outputFile).hasBinaryContent(dataForWriting);
}
@Test
public void whenUsingGuavaByteSinkMoreFiles_thenByteArrayIsWritten() throws IOException {
File outputFile = tempFolder.newFile("example-guava-bs.jpg");
ByteSink byteSink = MoreFiles.asByteSink(outputFile.toPath(), StandardOpenOption.CREATE, StandardOpenOption.WRITE);
byteSink.write(dataForWriting);
assertThat(outputFile).hasBinaryContent(dataForWriting);
}
@Test
public void whenUsingCommonsIo_thenByteArrayIsWritten() throws IOException {
File outputFile = tempFolder.newFile("example-file-utils.jpg");
FileUtils.writeByteArrayToFile(outputFile, dataForWriting);
assertThat(outputFile).hasBinaryContent(dataForWriting);
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

View File

@ -0,0 +1,2 @@
test-link*
0.*

View File

@ -0,0 +1,8 @@
## Core Java IO
This module contains articles about core Java input and output (IO)
### Relevant Articles:
- [Java File Separator vs File Path Separator](https://www.baeldung.com/java-file-vs-file-path-separator)
- [[<-- Prev]](/core-java-modules/core-java-io-3)

View File

@ -0,0 +1,52 @@
<?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-io-4</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-io-4</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent>
<dependencies>
<!-- utils -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<!-- logging -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
</build>
<properties>
<assertj.version>3.6.1</assertj.version>
</properties>
</project>

View File

@ -0,0 +1,63 @@
package com.baeldung.fileseparator;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.File;
import java.io.IOException;
import java.util.StringJoiner;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
public class FilePathSeparatorUnitTest {
@Test
@EnabledOnOs(OS.WINDOWS)
public void whenCheckPathSeparator_thenResultIsAsExpectedOnWindows() throws IOException {
assertEquals(";", File.pathSeparator);
assertEquals(';', File.pathSeparatorChar);
}
@Test
@EnabledOnOs({ OS.LINUX, OS.MAC })
public void whenCheckPathSeparator_thenResultIsAsExpected() throws IOException {
assertEquals(":", File.pathSeparator);
assertEquals(':', File.pathSeparatorChar);
}
@Test
@EnabledOnOs(OS.WINDOWS)
public void whenBuildPathUsingString_thenResultIsAsExpectedOnWindows() throws IOException {
String[] pathNames = { "path1", "path2", "path3" };
String path = String.join(File.pathSeparator, pathNames);
assertEquals("path1;path2;path3",path);
}
@Test
@EnabledOnOs({ OS.LINUX, OS.MAC })
public void whenBuildPathUsingString_thenResultIsAsExpected() throws IOException {
String[] pathNames = { "path1", "path2", "path3" };
String path = String.join(File.pathSeparator, pathNames);
assertEquals("path1:path2:path3", path);
}
@Test
@EnabledOnOs(OS.WINDOWS)
public void whenbuildPathUsingStringJoiner_thenResultIsAsExpectedOnWindows() throws IOException {
assertEquals("path1;path2", buildPathUsingStringJoiner("path1", "path2"));
}
@Test
@EnabledOnOs({ OS.LINUX, OS.MAC })
public void whenbuildPathUsingStringJoiner_thenResultIsAsExpected() throws IOException {
assertEquals("path1:path2", buildPathUsingStringJoiner("path1", "path2"));
}
private String buildPathUsingStringJoiner(String path1, String path2) {
StringJoiner joiner = new StringJoiner(File.pathSeparator);
joiner.add(path1);
joiner.add(path2);
return joiner.toString();
}
}

View File

@ -0,0 +1,63 @@
package com.baeldung.fileseparator;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.File;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
public class FileSeparatorUnitTest {
@Test
@EnabledOnOs(OS.WINDOWS)
public void whenCheckFileSeparator_thenCorrectOnWindows() {
assertEquals("\\", File.separator);
assertEquals('\\', File.separatorChar);
String fileSeparator = FileSystems.getDefault().getSeparator();
assertEquals("\\",fileSeparator);
}
@Test
@EnabledOnOs({ OS.LINUX, OS.MAC })
public void whenCheckFileSeparator_thenCorrect() {
assertEquals("/", File.separator);
assertEquals('/', File.separatorChar);
String fileSeparator = FileSystems.getDefault().getSeparator();
assertEquals("/",fileSeparator);
}
@Test
@EnabledOnOs(OS.WINDOWS)
public void whenBuildFilePathUsingPathsClass_thenCorrectOnWindows() {
Path path = Paths.get("dir1", "dir2");
assertEquals("dir1\\dir2", path.toString());
}
@Test
@EnabledOnOs({ OS.LINUX, OS.MAC })
public void whenBuildFilePathUsingPathsClass_thenCorrect() {
Path path = Paths.get("dir1", "dir2");
assertEquals("dir1/dir2", path.toString());
}
@Test
@EnabledOnOs(OS.WINDOWS)
public void whenBuildFilePathUsingFileClass_thenOutputIsAsExpectedOnWindows() {
File file = new File("file1", "file2");
assertEquals("file1\\file2", file.toString());
}
@Test
@EnabledOnOs({ OS.LINUX, OS.MAC })
public void whenBuildFilePathUsingFileClass_thenOutputIsAsExpected() {
File file = new File("file1", "file2");
assertEquals("file1/file2", file.toString());
}
}

View File

@ -11,4 +11,5 @@ This module contains articles about working with the Java Virtual Machine (JVM).
- [Where Is the Array Length Stored in JVM?](https://www.baeldung.com/java-jvm-array-length)
- [Memory Address of Objects in Java](https://www.baeldung.com/java-object-memory-address)
- [List All Classes Loaded in a Specific Class Loader](https://www.baeldung.com/java-list-classes-class-loader)
- [An Introduction to the Constant Pool in the JVM](https://www.baeldung.com/jvm-constant-pool)
- More articles: [[<-- prev]](/core-java-modules/core-java-jvm)

View File

@ -0,0 +1,8 @@
package com.baeldung.constantpool;
public class ConstantPool {
public void sayHello() {
System.out.println("Hello World");
}
}

View File

@ -69,7 +69,6 @@
<jmh-generator.version>1.19</jmh-generator.version>
<assertj.version>3.12.2</assertj.version>
<commons.beanutils.version>1.9.4</commons.beanutils.version>
<commons-lang3.version>3.10</commons-lang3.version>
<guava.version>29.0-jre</guava.version>
</properties>

View File

@ -9,4 +9,7 @@ This module contains articles about core features in the Java language
- [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)
- [The transient Keyword in Java](https://www.baeldung.com/java-transient-keyword)
- [How to Access an Iteration Counter in a For Each Loop](https://www.baeldung.com/java-foreach-counter)
- [Comparing Doubles in Java](https://www.baeldung.com/java-comparing-doubles)
- [Guide to Implementing the compareTo Method](https://www.baeldung.com/java-compareto)
- [[<-- Prev]](/core-java-modules/core-java-lang-2)

View File

@ -23,6 +23,18 @@
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>3.6.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>

View File

@ -0,0 +1,16 @@
package com.baeldung.compareto;
public class BankAccount implements Comparable<BankAccount> {
private final int balance;
public BankAccount(int balance) {
this.balance = balance;
}
@Override
public int compareTo(BankAccount anotherAccount) {
return this.balance - anotherAccount.balance;
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.compareto;
public class BankAccountFix implements Comparable<BankAccountFix> {
private final int balance;
public BankAccountFix(int balance) {
this.balance = balance;
}
@Override
public int compareTo(BankAccountFix anotherAccount) {
return Integer.compare(this.balance, anotherAccount.balance);
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.compareto;
public class FootballPlayer implements Comparable<FootballPlayer> {
private final String name;
private final int goalsScored;
public FootballPlayer(String name, int goalsScored) {
this.name = name;
this.goalsScored = goalsScored;
}
public String getName() {
return name;
}
@Override
public int compareTo(FootballPlayer anotherPlayer) {
return Integer.compare(this.goalsScored, anotherPlayer.goalsScored);
}
@Override
public boolean equals(Object object) {
if (this == object)
return true;
if (object == null || getClass() != object.getClass())
return false;
FootballPlayer player = (FootballPlayer) object;
return name.equals(player.name);
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.compareto;
public class HandballPlayer {
private final String name;
private final int height;
public HandballPlayer(String name, int height) {
this.name = name;
this.height = height;
}
}

View File

@ -0,0 +1,71 @@
package com.baeldung.comparedouble;
import com.google.common.math.DoubleMath;
import org.apache.commons.math3.util.Precision;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
public class CompareDoubleUnitTest {
@Test
public void givenDoubleValuesThatShouldHaveSameValue_whenUsingSimpleComparison_thenFails() {
double d1 = getFirstDouble(0);
double d2 = .1 * 8;
assertThat(d1 == d2).isFalse();
}
@Test
public void givenDoubleValuesThatShouldHaveSameValue_whenUsingThresholdComparison_thenSuccess() {
double d1 = getFirstDouble(0);
double d2 = .1 * 8;
double epsilon = 0.000001d;
assertThat(Math.abs(d1 - d2) < epsilon).isTrue();
}
@Test
public void givenDoubleValuesThatShouldHaveSameValue_whenUsingGuavaFuzzyComparison_thenSuccess() {
double d1 = getFirstDouble(0);
double d2 = .1 * 8;
double epsilon = 0.000001d;
assertThat(DoubleMath.fuzzyEquals(d1, d2, epsilon)).isTrue();
}
@Test
public void givenDoubleValuesThatShouldHaveSameValue_whenUsingCommonsMathComparison_thenSuccess() {
double d1 = getFirstDouble(0);
double d2 = .1 * 8;
double epsilon = 0.000001d;
assertThat(Precision.equals(d1, d2, epsilon)).isTrue();
assertThat(Precision.equals(d1, d2)).isTrue();
}
@Test
public void givenDoubleValuesThatShouldHaveSameValue_whenUsingJunitComparison_thenSuccess() {
double d1 = getFirstDouble(0);
double d2 = .1 * 8;
double epsilon = 0.000001d;
assertEquals(d1, d2, epsilon);
}
private double getFirstDouble(double d1) {
for (int i = 1; i <= 8; i++) {
d1 += .1;
}
return d1;
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.compareto;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import static org.assertj.core.api.Assertions.assertThat;
public class ArraysSortingUnitTest {
@Test
public void givenArrayOfNumbers_whenSortingArray_thenNumbersAreSortedAscending() {
int[] numbers = new int[] {5, 3, 9, 11, 1, 7};
Arrays.sort(numbers);
assertThat(numbers).containsExactly(1, 3, 5, 7, 9, 11);
}
@Test
public void givenArrayOfStrings_whenSortingArray_thenStringsAreSortedAlphabetically() {
String[] players = new String[] {"ronaldo", "modric", "ramos", "messi"};
Arrays.sort(players);
assertThat(players).containsExactly("messi", "modric", "ramos", "ronaldo");
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.compareto;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class BankAccountFixUnitTest {
@Test
public void givenComparisonBasedImpl_whenUsingSmallIntegers_thenComparisonWorks() {
BankAccountFix accountOne = new BankAccountFix(5000);
BankAccountFix accountTwo = new BankAccountFix(1000);
int comparison = accountOne.compareTo(accountTwo);
assertThat(comparison).isPositive();
}
@Test
public void givenComparisonBasedImpl_whenUsingLargeIntegers_thenComparisonWorks() {
BankAccountFix accountOne = new BankAccountFix(1900000000);
BankAccountFix accountTwo = new BankAccountFix(-2000000000);
int comparison = accountOne.compareTo(accountTwo);
assertThat(comparison).isPositive();
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.compareto;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.*;
public class BankAccountUnitTest {
@Test
public void givenSubtractionBasedImpl_whenUsingSmallIntegers_thenComparisonWorks() {
BankAccount accountOne = new BankAccount(5000);
BankAccount accountTwo = new BankAccount(1000);
int comparison = accountOne.compareTo(accountTwo);
assertThat(comparison).isPositive();
}
@Test
public void givenSubtractionBasedImpl_whenUsingLargeIntegers_thenComparisonBreaks() {
BankAccount accountOne = new BankAccount(1900000000);
BankAccount accountTwo = new BankAccount(-2000000000);
int comparison = accountOne.compareTo(accountTwo);
assertThat(comparison).isNegative();
}
}

View File

@ -0,0 +1,57 @@
package com.baeldung.compareto;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;
import static org.assertj.core.api.Assertions.assertThat;
public class FootballPlayerUnitTest {
@Test
public void givenInconsistentCompareToAndEqualsImpl_whenUsingSortedSet_thenSomeElementsAreNotAdded() {
FootballPlayer messi = new FootballPlayer("Messi", 800);
FootballPlayer ronaldo = new FootballPlayer("Ronaldo", 800);
TreeSet<FootballPlayer> set = new TreeSet<>();
set.add(messi);
set.add(ronaldo);
assertThat(set).hasSize(1);
assertThat(set).doesNotContain(ronaldo);
}
@Test
public void givenCompareToImpl_whenUsingCustomComparator_thenComparatorLogicIsApplied() {
FootballPlayer ronaldo = new FootballPlayer("Ronaldo", 900);
FootballPlayer messi = new FootballPlayer("Messi", 800);
FootballPlayer modric = new FootballPlayer("Modric", 100);
List<FootballPlayer> players = Arrays.asList(ronaldo, messi, modric);
Comparator<FootballPlayer> nameComparator = Comparator.comparing(FootballPlayer::getName);
Collections.sort(players, nameComparator);
assertThat(players).containsExactly(messi, modric, ronaldo);
}
@Test
public void givenCompareToImpl_whenSavingElementsInTreeMap_thenKeysAreSortedUsingCompareTo() {
FootballPlayer ronaldo = new FootballPlayer("Ronaldo", 900);
FootballPlayer messi = new FootballPlayer("Messi", 800);
FootballPlayer modric = new FootballPlayer("Modric", 100);
Map<FootballPlayer, String> players = new TreeMap<>();
players.put(ronaldo, "forward");
players.put(messi, "forward");
players.put(modric, "midfielder");
assertThat(players.keySet()).containsExactly(modric, messi, ronaldo);
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.compareto;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
public class HandballPlayerUnitTest {
@Test
public void givenComparableIsNotImplemented_whenSortingArray_thenExceptionIsThrown() {
HandballPlayer duvnjak = new HandballPlayer("Duvnjak", 197);
HandballPlayer hansen = new HandballPlayer("Hansen", 196);
HandballPlayer[] players = new HandballPlayer[] {duvnjak, hansen};
assertThatExceptionOfType(ClassCastException.class).isThrownBy(() -> Arrays.sort(players));
}
}

View File

@ -14,4 +14,4 @@
- [Debugging with Eclipse](https://www.baeldung.com/eclipse-debugging)
- [Matrix Multiplication in Java](https://www.baeldung.com/java-matrix-multiplication)
- [Largest Power of 2 That Is Less Than the Given Number with Java](https://www.baeldung.com/java-largest-power-of-2-less-than-number)
- More articles: [[<-- Prev]](/core-java-modules/core-java-lang-math)
- More articles: [[<-- Prev]](/core-java-modules/core-java-lang-math)[[Next -->]](/core-java-modules/core-java-lang-math-3)

View File

@ -0,0 +1,8 @@
=========
## Core Java 8 Cookbooks and Examples - Part 3
### Relevant articles:
- [Evaluating a Math Expression in Java](https://www.baeldung.com/java-evaluate-math-expression-string)
- More articles: [[<-- Prev]](/core-java-modules/core-java-lang-math-2)

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