Merge branch 'master' of https://github.com/vikasrajput6035/tutorials into BAEL-4936
This commit is contained in:
@@ -5,7 +5,10 @@ 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)
|
||||
- [Converting between a List and a Set in Java](https://www.baeldung.com/convert-list-to-set-and-set-to-list)
|
||||
- [Java IndexOutOfBoundsException “Source Does Not Fit in Dest”](https://www.baeldung.com/java-indexoutofboundsexception)
|
||||
- [Collect a Java Stream to an Immutable Collection](https://www.baeldung.com/java-stream-immutable-collection)
|
||||
|
||||
@@ -1,22 +1,29 @@
|
||||
<?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">
|
||||
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-10</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-10</name>
|
||||
<packaging>jar</packaging>
|
||||
<url>http://maven.apache.org</url>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../</relativePath>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>${commons-collections4.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
@@ -34,6 +41,7 @@
|
||||
<properties>
|
||||
<maven.compiler.source.version>10</maven.compiler.source.version>
|
||||
<maven.compiler.target.version>10</maven.compiler.target.version>
|
||||
<commons-collections4.version>4.1</commons-collections4.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
+3
-3
@@ -7,7 +7,7 @@ import junit.framework.TestSuite;
|
||||
/**
|
||||
* Unit test for simple App.
|
||||
*/
|
||||
public class AppTest
|
||||
public class AppUnitTest
|
||||
extends TestCase
|
||||
{
|
||||
/**
|
||||
@@ -15,7 +15,7 @@ public class AppTest
|
||||
*
|
||||
* @param testName name of the test case
|
||||
*/
|
||||
public AppTest( String testName )
|
||||
public AppUnitTest(String testName )
|
||||
{
|
||||
super( testName );
|
||||
}
|
||||
@@ -25,7 +25,7 @@ public class AppTest
|
||||
*/
|
||||
public static Test suite()
|
||||
{
|
||||
return new TestSuite( AppTest.class );
|
||||
return new TestSuite( AppUnitTest.class );
|
||||
}
|
||||
|
||||
/**
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
package com.baeldung.java10.collections.conversion;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.collect.Sets;
|
||||
import org.apache.commons.collections4.CollectionUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
public class ListSetConversionUnitTest {
|
||||
|
||||
// Set -> List; List -> Set
|
||||
|
||||
@Test
|
||||
public final void givenUsingCoreJava_whenSetConvertedToList_thenCorrect() {
|
||||
final Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
|
||||
final List<Integer> targetList = new ArrayList<>(sourceSet);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingCoreJava_whenListConvertedToSet_thenCorrect() {
|
||||
final List<Integer> sourceList = Lists.newArrayList(0, 1, 2, 3, 4, 5);
|
||||
final Set<Integer> targetSet = new HashSet<>(sourceList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingJava10_whenSetConvertedToList_thenCorrect() {
|
||||
final Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
|
||||
final List<Integer> targetList = List.copyOf(sourceSet);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingJava10_whenListConvertedToSet_thenCorrect() {
|
||||
final List<Integer> sourceList = Lists.newArrayList(0, 1, 2, 3, 4, 5);
|
||||
final Set<Integer> targetSet = Set.copyOf(sourceList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingGuava_whenSetConvertedToList_thenCorrect() {
|
||||
final Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
|
||||
final List<Integer> targetList = Lists.newArrayList(sourceSet);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingGuava_whenListConvertedToSet_thenCorrect() {
|
||||
final List<Integer> sourceList = Lists.newArrayList(0, 1, 2, 3, 4, 5);
|
||||
final Set<Integer> targetSet = Sets.newHashSet(sourceList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingCommonsCollections_whenListConvertedToSet_thenCorrect() {
|
||||
final List<Integer> sourceList = Lists.newArrayList(0, 1, 2, 3, 4, 5);
|
||||
|
||||
final Set<Integer> targetSet = new HashSet<>(6);
|
||||
CollectionUtils.addAll(targetSet, sourceList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingCommonsCollections_whenSetConvertedToList_thenCorrect() {
|
||||
final Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
|
||||
|
||||
final List<Integer> targetList = new ArrayList<>(6);
|
||||
CollectionUtils.addAll(targetList, sourceSet);
|
||||
}
|
||||
}
|
||||
+1
@@ -10,5 +10,6 @@ public class CopyListServiceUnitTest {
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void whenModifyCopyOfList_thenThrowsException() {
|
||||
List<Integer> copyList = List.copyOf(Arrays.asList(1, 2, 3, 4));
|
||||
copyList.add(4);
|
||||
}
|
||||
}
|
||||
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.java10.streams;
|
||||
|
||||
import static java.util.stream.Collectors.toUnmodifiableList;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class StreamToImmutableJava10UnitTest {
|
||||
|
||||
@Test
|
||||
public void whenUsingCollectorsToUnmodifiableList_thenSuccess() {
|
||||
List<String> givenList = Arrays.asList("a", "b", "c");
|
||||
List<String> result = givenList.stream()
|
||||
.collect(toUnmodifiableList());
|
||||
|
||||
System.out.println(result.getClass());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
## Core Java 11
|
||||
|
||||
This module contains articles about Java 11 core features
|
||||
|
||||
### Relevant articles
|
||||
- [Guide to Java 8 Optional](https://www.baeldung.com/java-optional)
|
||||
- [Guide to Java Reflection](http://www.baeldung.com/java-reflection)
|
||||
- [Guide to Java 8’s Collectors](https://www.baeldung.com/java-8-collectors)
|
||||
- [New Features in Java 11](https://www.baeldung.com/java-11-new-features)
|
||||
@@ -0,0 +1,79 @@
|
||||
<?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-11-2</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-11-2</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../..</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<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>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${maven.compiler.source.version}</source>
|
||||
<target>${maven.compiler.target.version}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<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>
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.java.reflection;
|
||||
package com.baeldung.reflection;
|
||||
|
||||
public abstract class Animal implements Eating {
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.java.reflection;
|
||||
package com.baeldung.reflection;
|
||||
|
||||
public class Bird extends Animal {
|
||||
private boolean walks;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.java.reflection;
|
||||
package com.baeldung.reflection;
|
||||
|
||||
import java.lang.annotation.Annotation;
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.java.reflection;
|
||||
package com.baeldung.reflection;
|
||||
|
||||
public interface Eating {
|
||||
String eats();
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.java.reflection;
|
||||
package com.baeldung.reflection;
|
||||
|
||||
public class Goat extends Animal implements Locomotion {
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.java.reflection;
|
||||
package com.baeldung.reflection;
|
||||
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.java.reflection;
|
||||
package com.baeldung.reflection;
|
||||
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.lang.reflect.Field;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.java.reflection;
|
||||
package com.baeldung.reflection;
|
||||
|
||||
@Greeter(greet="Good morning")
|
||||
public class Greetings {
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.java.reflection;
|
||||
package com.baeldung.reflection;
|
||||
|
||||
public interface Locomotion {
|
||||
String getLocomotion();
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.java.reflection;
|
||||
package com.baeldung.reflection;
|
||||
|
||||
public class Operations {
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.java.reflection;
|
||||
package com.baeldung.reflection;
|
||||
|
||||
public class Person {
|
||||
private String name;
|
||||
+28
-22
@@ -1,18 +1,11 @@
|
||||
package com.baeldung.streams.collectors;
|
||||
package com.baeldung.collectors;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.common.collect.Sets;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.DoubleSummaryStatistics;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.*;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.BinaryOperator;
|
||||
import java.util.function.Function;
|
||||
@@ -20,19 +13,7 @@ import java.util.function.Supplier;
|
||||
import java.util.stream.Collector;
|
||||
|
||||
import static com.google.common.collect.Sets.newHashSet;
|
||||
import static java.util.stream.Collectors.averagingDouble;
|
||||
import static java.util.stream.Collectors.collectingAndThen;
|
||||
import static java.util.stream.Collectors.counting;
|
||||
import static java.util.stream.Collectors.groupingBy;
|
||||
import static java.util.stream.Collectors.joining;
|
||||
import static java.util.stream.Collectors.maxBy;
|
||||
import static java.util.stream.Collectors.partitioningBy;
|
||||
import static java.util.stream.Collectors.summarizingDouble;
|
||||
import static java.util.stream.Collectors.summingDouble;
|
||||
import static java.util.stream.Collectors.toCollection;
|
||||
import static java.util.stream.Collectors.toList;
|
||||
import static java.util.stream.Collectors.toMap;
|
||||
import static java.util.stream.Collectors.toSet;
|
||||
import static java.util.stream.Collectors.*;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
@@ -48,6 +29,14 @@ public class Java8CollectorsUnitTest {
|
||||
assertThat(result).containsAll(givenList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingToUnmodifiableList_shouldCollectToUnmodifiableList() {
|
||||
final List<String> result = givenList.stream().collect(toUnmodifiableList());
|
||||
|
||||
assertThatThrownBy(() -> result.add("foo"))
|
||||
.isInstanceOf(UnsupportedOperationException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingToSet_shouldCollectToSet() throws Exception {
|
||||
final Set<String> result = givenList.stream().collect(toSet());
|
||||
@@ -55,6 +44,14 @@ public class Java8CollectorsUnitTest {
|
||||
assertThat(result).containsAll(givenList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingToUnmodifiableSet_shouldCollectToUnmodifiableSet() {
|
||||
final Set<String> result = givenList.stream().collect(toUnmodifiableSet());
|
||||
|
||||
assertThatThrownBy(() -> result.add("foo"))
|
||||
.isInstanceOf(UnsupportedOperationException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenContainsDuplicateElements_whenCollectingToSet_shouldAddDuplicateElementsOnlyOnce() throws Exception {
|
||||
final Set<String> result = listWithDuplicates.stream().collect(toSet());
|
||||
@@ -84,6 +81,15 @@ public class Java8CollectorsUnitTest {
|
||||
assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingToUnmodifiableMap_shouldCollectToUnmodifiableMap() {
|
||||
final Map<String, Integer> result = givenList.stream()
|
||||
.collect(toUnmodifiableMap(Function.identity(), String::length));
|
||||
|
||||
assertThatThrownBy(() -> result.put("foo", 3))
|
||||
.isInstanceOf(UnsupportedOperationException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingToMapwWithDuplicates_shouldCollectToMapMergingTheIdenticalItems() throws Exception {
|
||||
final Map<String, Integer> result = listWithDuplicates.stream().collect(
|
||||
+54
@@ -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!");
|
||||
}
|
||||
|
||||
}
|
||||
+61
@@ -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");
|
||||
}
|
||||
|
||||
}
|
||||
+37
@@ -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());
|
||||
}
|
||||
|
||||
}
|
||||
+3
-1
@@ -7,7 +7,9 @@ import java.util.Optional;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class OptionalChainingUnitTest {
|
||||
|
||||
+9
-1
@@ -9,7 +9,9 @@ import java.util.List;
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class OptionalUnitTest {
|
||||
|
||||
@@ -262,6 +264,12 @@ public class OptionalUnitTest {
|
||||
.orElseThrow(IllegalArgumentException::new);
|
||||
}
|
||||
|
||||
@Test(expected = NoSuchElementException.class)
|
||||
public void whenNoArgOrElseThrowWorks_thenCorrect() {
|
||||
String nullName = null;
|
||||
String name = Optional.ofNullable(nullName).orElseThrow();
|
||||
}
|
||||
|
||||
public String getMyDefault() {
|
||||
LOG.debug("Getting default value...");
|
||||
return "Default Value";
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.java.reflection;
|
||||
package com.baeldung.reflection;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
+33
-40
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.java.reflection;
|
||||
package com.baeldung.reflection;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
@@ -32,23 +32,23 @@ public class ReflectionUnitTest {
|
||||
final Class<?> clazz = goat.getClass();
|
||||
|
||||
assertEquals("Goat", clazz.getSimpleName());
|
||||
assertEquals("com.baeldung.java.reflection.Goat", clazz.getName());
|
||||
assertEquals("com.baeldung.java.reflection.Goat", clazz.getCanonicalName());
|
||||
assertEquals("com.baeldung.reflection.Goat", clazz.getName());
|
||||
assertEquals("com.baeldung.reflection.Goat", clazz.getCanonicalName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenClassName_whenCreatesObject_thenCorrect() throws ClassNotFoundException {
|
||||
final Class<?> clazz = Class.forName("com.baeldung.java.reflection.Goat");
|
||||
final Class<?> clazz = Class.forName("com.baeldung.reflection.Goat");
|
||||
|
||||
assertEquals("Goat", clazz.getSimpleName());
|
||||
assertEquals("com.baeldung.java.reflection.Goat", clazz.getName());
|
||||
assertEquals("com.baeldung.java.reflection.Goat", clazz.getCanonicalName());
|
||||
assertEquals("com.baeldung.reflection.Goat", clazz.getName());
|
||||
assertEquals("com.baeldung.reflection.Goat", clazz.getCanonicalName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenClass_whenRecognisesModifiers_thenCorrect() throws ClassNotFoundException {
|
||||
final Class<?> goatClass = Class.forName("com.baeldung.java.reflection.Goat");
|
||||
final Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
|
||||
final Class<?> goatClass = Class.forName("com.baeldung.reflection.Goat");
|
||||
final Class<?> animalClass = Class.forName("com.baeldung.reflection.Animal");
|
||||
final int goatMods = goatClass.getModifiers();
|
||||
final int animalMods = animalClass.getModifiers();
|
||||
|
||||
@@ -63,7 +63,7 @@ public class ReflectionUnitTest {
|
||||
final Class<?> goatClass = goat.getClass();
|
||||
final Package pkg = goatClass.getPackage();
|
||||
|
||||
assertEquals("com.baeldung.java.reflection", pkg.getName());
|
||||
assertEquals("com.baeldung.reflection", pkg.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -81,8 +81,8 @@ public class ReflectionUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenClass_whenGetsImplementedInterfaces_thenCorrect() throws ClassNotFoundException {
|
||||
final Class<?> goatClass = Class.forName("com.baeldung.java.reflection.Goat");
|
||||
final Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
|
||||
final Class<?> goatClass = Class.forName("com.baeldung.reflection.Goat");
|
||||
final Class<?> animalClass = Class.forName("com.baeldung.reflection.Animal");
|
||||
final Class<?>[] goatInterfaces = goatClass.getInterfaces();
|
||||
final Class<?>[] animalInterfaces = animalClass.getInterfaces();
|
||||
|
||||
@@ -94,16 +94,16 @@ public class ReflectionUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenClass_whenGetsConstructor_thenCorrect() throws ClassNotFoundException {
|
||||
final Class<?> goatClass = Class.forName("com.baeldung.java.reflection.Goat");
|
||||
final Class<?> goatClass = Class.forName("com.baeldung.reflection.Goat");
|
||||
final Constructor<?>[] constructors = goatClass.getConstructors();
|
||||
|
||||
assertEquals(1, constructors.length);
|
||||
assertEquals("com.baeldung.java.reflection.Goat", constructors[0].getName());
|
||||
assertEquals("com.baeldung.reflection.Goat", constructors[0].getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenClass_whenGetsFields_thenCorrect() throws ClassNotFoundException {
|
||||
final Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
|
||||
final Class<?> animalClass = Class.forName("com.baeldung.reflection.Animal");
|
||||
final Field[] fields = animalClass.getDeclaredFields();
|
||||
|
||||
final List<String> actualFields = getFieldNames(fields);
|
||||
@@ -114,7 +114,7 @@ public class ReflectionUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenClass_whenGetsMethods_thenCorrect() throws ClassNotFoundException {
|
||||
final Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
|
||||
final Class<?> animalClass = Class.forName("com.baeldung.reflection.Animal");
|
||||
final Method[] methods = animalClass.getDeclaredMethods();
|
||||
final List<String> actualMethods = getMethodNames(methods);
|
||||
|
||||
@@ -124,7 +124,7 @@ public class ReflectionUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenClass_whenGetsAllConstructors_thenCorrect() throws ClassNotFoundException {
|
||||
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||
final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
|
||||
final Constructor<?>[] constructors = birdClass.getConstructors();
|
||||
|
||||
assertEquals(3, constructors.length);
|
||||
@@ -132,7 +132,7 @@ public class ReflectionUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenClass_whenGetsEachConstructorByParamTypes_thenCorrect() throws Exception {
|
||||
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||
final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
|
||||
birdClass.getConstructor();
|
||||
birdClass.getConstructor(String.class);
|
||||
birdClass.getConstructor(String.class, boolean.class);
|
||||
@@ -140,7 +140,7 @@ public class ReflectionUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenClass_whenInstantiatesObjectsAtRuntime_thenCorrect() throws Exception {
|
||||
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||
final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
|
||||
|
||||
final Constructor<?> cons1 = birdClass.getConstructor();
|
||||
final Constructor<?> cons2 = birdClass.getConstructor(String.class);
|
||||
@@ -159,7 +159,7 @@ public class ReflectionUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenClass_whenGetsPublicFields_thenCorrect() throws ClassNotFoundException {
|
||||
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||
final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
|
||||
final Field[] fields = birdClass.getFields();
|
||||
assertEquals(1, fields.length);
|
||||
assertEquals("CATEGORY", fields[0].getName());
|
||||
@@ -168,7 +168,7 @@ public class ReflectionUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenClass_whenGetsPublicFieldByName_thenCorrect() throws Exception {
|
||||
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||
final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
|
||||
final Field field = birdClass.getField("CATEGORY");
|
||||
assertEquals("CATEGORY", field.getName());
|
||||
|
||||
@@ -176,7 +176,7 @@ public class ReflectionUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenClass_whenGetsDeclaredFields_thenCorrect() throws ClassNotFoundException {
|
||||
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||
final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
|
||||
final Field[] fields = birdClass.getDeclaredFields();
|
||||
assertEquals(1, fields.length);
|
||||
assertEquals("walks", fields[0].getName());
|
||||
@@ -184,7 +184,7 @@ public class ReflectionUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenClass_whenGetsFieldsByName_thenCorrect() throws Exception {
|
||||
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||
final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
|
||||
final Field field = birdClass.getDeclaredField("walks");
|
||||
assertEquals("walks", field.getName());
|
||||
|
||||
@@ -192,14 +192,14 @@ public class ReflectionUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenClassField_whenGetsType_thenCorrect() throws Exception {
|
||||
final Field field = Class.forName("com.baeldung.java.reflection.Bird").getDeclaredField("walks");
|
||||
final Field field = Class.forName("com.baeldung.reflection.Bird").getDeclaredField("walks");
|
||||
final Class<?> fieldClass = field.getType();
|
||||
assertEquals("boolean", fieldClass.getSimpleName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenClassField_whenSetsAndGetsValue_thenCorrect() throws Exception {
|
||||
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||
final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
|
||||
final Bird bird = (Bird) birdClass.getConstructor().newInstance();
|
||||
final Field field = birdClass.getDeclaredField("walks");
|
||||
field.setAccessible(true);
|
||||
@@ -216,7 +216,7 @@ public class ReflectionUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenClassField_whenGetsAndSetsWithNull_thenCorrect() throws Exception {
|
||||
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||
final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
|
||||
final Field field = birdClass.getField("CATEGORY");
|
||||
field.setAccessible(true);
|
||||
|
||||
@@ -225,7 +225,7 @@ public class ReflectionUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenClass_whenGetsAllPublicMethods_thenCorrect() throws ClassNotFoundException {
|
||||
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||
final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
|
||||
final Method[] methods = birdClass.getMethods();
|
||||
final List<String> methodNames = getMethodNames(methods);
|
||||
|
||||
@@ -235,7 +235,7 @@ public class ReflectionUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenClass_whenGetsOnlyDeclaredMethods_thenCorrect() throws ClassNotFoundException {
|
||||
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||
final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
|
||||
final List<String> actualMethodNames = getMethodNames(birdClass.getDeclaredMethods());
|
||||
|
||||
final List<String> expectedMethodNames = Arrays.asList("setWalks", "walks", "getSound", "eats");
|
||||
@@ -248,24 +248,17 @@ public class ReflectionUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenMethodName_whenGetsMethod_thenCorrect() throws Exception {
|
||||
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||
final Method walksMethod = birdClass.getDeclaredMethod("walks");
|
||||
final Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", boolean.class);
|
||||
|
||||
assertFalse(walksMethod.isAccessible());
|
||||
assertFalse(setWalksMethod.isAccessible());
|
||||
|
||||
walksMethod.setAccessible(true);
|
||||
setWalksMethod.setAccessible(true);
|
||||
|
||||
assertTrue(walksMethod.isAccessible());
|
||||
assertTrue(setWalksMethod.isAccessible());
|
||||
final Bird bird = new Bird();
|
||||
final Method walksMethod = bird.getClass().getDeclaredMethod("walks");
|
||||
final Method setWalksMethod = bird.getClass().getDeclaredMethod("setWalks", boolean.class);
|
||||
|
||||
assertTrue(walksMethod.canAccess(bird));
|
||||
assertTrue(setWalksMethod.canAccess(bird));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMethod_whenInvokes_thenCorrect() throws Exception {
|
||||
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||
final Class<?> birdClass = Class.forName("com.baeldung.reflection.Bird");
|
||||
final Bird bird = (Bird) birdClass.getConstructor().newInstance();
|
||||
final Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", boolean.class);
|
||||
final Method walksMethod = birdClass.getDeclaredMethod("walks");
|
||||
@@ -8,7 +8,7 @@ This module contains articles about Java 11 core features
|
||||
- [Java 11 Local Variable Syntax for Lambda Parameters](https://www.baeldung.com/java-var-lambda-params)
|
||||
- [Java 11 String API Additions](https://www.baeldung.com/java-11-string-api)
|
||||
- [Java 11 Nest Based Access Control](https://www.baeldung.com/java-nest-based-access-control)
|
||||
- [Exploring the New HTTP Client in Java 9 and 11](https://www.baeldung.com/java-9-http-client)
|
||||
- [Exploring the New HTTP Client in Java](https://www.baeldung.com/java-9-http-client)
|
||||
- [An Introduction to Epsilon GC: A No-Op Experimental Garbage Collector](https://www.baeldung.com/jvm-epsilon-gc-garbage-collector)
|
||||
- [Guide to jlink](https://www.baeldung.com/jlink)
|
||||
- [Negate a Predicate Method Reference with Java 11](https://www.baeldung.com/java-negate-predicate-method-reference)
|
||||
|
||||
@@ -32,12 +32,12 @@
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>${jmh.version}</version>
|
||||
<version>${jmh-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${jmh.version}</version>
|
||||
<version>${jmh-generator.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@@ -105,9 +105,8 @@
|
||||
<guava.version>27.1-jre</guava.version>
|
||||
<assertj.version>3.11.1</assertj.version>
|
||||
<uberjar.name>benchmarks</uberjar.name>
|
||||
<jmh.version>1.22</jmh.version>
|
||||
<eclipse.collections.version>10.0.0</eclipse.collections.version>
|
||||
<shade.plugin.version>10.0.0</shade.plugin.version>
|
||||
<shade.plugin.version>3.2.4</shade.plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
+1
-1
@@ -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
|
||||
|
||||
+7
-1
@@ -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"))
|
||||
|
||||
@@ -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)
|
||||
|
||||
+21
@@ -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));
|
||||
}
|
||||
}
|
||||
+32
@@ -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);
|
||||
}
|
||||
}
|
||||
+15
@@ -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);
|
||||
}
|
||||
}
|
||||
+18
@@ -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);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -5,7 +5,7 @@ import static org.hamcrest.MatcherAssert.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class StringAPITest {
|
||||
public class StringAPIUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenPositiveArgument_thenReturnIndentedString() {
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -44,6 +44,8 @@
|
||||
<configuration>
|
||||
<release>${maven.compiler.release}</release>
|
||||
<compilerArgs>--enable-preview</compilerArgs>
|
||||
<source>14</source>
|
||||
<target>14</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.java14.character;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
|
||||
public class IsLetterOrAlphabetUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenACharacter_whenLetter_thenAssertIsLetterTrue() {
|
||||
assertTrue(Character.isLetter(65));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACharacter_whenLetter_thenAssertIsAlphabeticTrue() {
|
||||
assertTrue(Character.isAlphabetic(65));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACharacter_whenAlphabeticAndNotLetter_thenAssertIsLetterFalse() {
|
||||
assertFalse(Character.isLetter(837));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACharacter_whenAlphabeticAndNotLetter_thenAssertIsAlphabeticTrue() {
|
||||
assertTrue(Character.isAlphabetic(837));
|
||||
}
|
||||
|
||||
}
|
||||
+26
@@ -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"));
|
||||
}
|
||||
|
||||
}
|
||||
+38
@@ -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"));
|
||||
}
|
||||
|
||||
}
|
||||
+50
@@ -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);
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
+1
-1
@@ -7,7 +7,7 @@ import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class PersonTest {
|
||||
public class PersonUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenSameNameAndAddress_whenEquals_thenPersonsEqual() {
|
||||
@@ -0,0 +1 @@
|
||||
--enable-preview
|
||||
@@ -0,0 +1,7 @@
|
||||
## Core Java 15
|
||||
|
||||
This module contains articles about Java 15.
|
||||
|
||||
### Relevant articles
|
||||
|
||||
- [Sealed Classes and Interfaces in Java 15](https://www.baeldung.com/java-sealed-classes-interfaces)
|
||||
@@ -0,0 +1,76 @@
|
||||
<?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-15</artifactId>
|
||||
<name>core-java-15</name>
|
||||
<packaging>jar</packaging>
|
||||
<url>http://maven.apache.org</url>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</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-api</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<release>${maven.compiler.release}</release>
|
||||
<compilerArgs>--enable-preview</compilerArgs>
|
||||
<source>14</source>
|
||||
<target>14</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${surefire.plugin.version}</version>
|
||||
<configuration>
|
||||
<argLine>--enable-preview</argLine>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.release>15</maven.compiler.release>
|
||||
<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>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package com.baeldung.sealed.alternative;
|
||||
|
||||
public class Vehicles {
|
||||
|
||||
abstract static class Vehicle {
|
||||
|
||||
private final String registrationNumber;
|
||||
|
||||
public Vehicle(String registrationNumber) {
|
||||
this.registrationNumber = registrationNumber;
|
||||
}
|
||||
|
||||
public String getRegistrationNumber() {
|
||||
return registrationNumber;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static final class Car extends Vehicle {
|
||||
|
||||
private final int numberOfSeats;
|
||||
|
||||
public Car(int numberOfSeats, String registrationNumber) {
|
||||
super(registrationNumber);
|
||||
this.numberOfSeats = numberOfSeats;
|
||||
}
|
||||
|
||||
public int getNumberOfSeats() {
|
||||
return numberOfSeats;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static final class Truck extends Vehicle {
|
||||
|
||||
private final int loadCapacity;
|
||||
|
||||
public Truck(int loadCapacity, String registrationNumber) {
|
||||
super(registrationNumber);
|
||||
this.loadCapacity = loadCapacity;
|
||||
}
|
||||
|
||||
public int getLoadCapacity() {
|
||||
return loadCapacity;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.sealed.classes;
|
||||
|
||||
public non-sealed class Car extends Vehicle implements Service {
|
||||
|
||||
private final int numberOfSeats;
|
||||
|
||||
public Car(int numberOfSeats, String registrationNumber) {
|
||||
super(registrationNumber);
|
||||
this.numberOfSeats = numberOfSeats;
|
||||
}
|
||||
|
||||
public int getNumberOfSeats() {
|
||||
return numberOfSeats;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getMaxServiceIntervalInMonths() {
|
||||
return 12;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.sealed.classes;
|
||||
|
||||
public sealed interface Service permits Car, Truck {
|
||||
|
||||
int getMaxServiceIntervalInMonths();
|
||||
|
||||
default int getMaxDistanceBetweenServicesInKilometers() {
|
||||
return 100000;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.sealed.classes;
|
||||
|
||||
public final class Truck extends Vehicle implements Service {
|
||||
|
||||
private final int loadCapacity;
|
||||
|
||||
public Truck(int loadCapacity, String registrationNumber) {
|
||||
super(registrationNumber);
|
||||
this.loadCapacity = loadCapacity;
|
||||
}
|
||||
|
||||
public int getLoadCapacity() {
|
||||
return loadCapacity;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getMaxServiceIntervalInMonths() {
|
||||
return 18;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.sealed.classes;
|
||||
|
||||
public abstract sealed class Vehicle permits Car, Truck {
|
||||
|
||||
protected final String registrationNumber;
|
||||
|
||||
public Vehicle(String registrationNumber) {
|
||||
this.registrationNumber = registrationNumber;
|
||||
}
|
||||
|
||||
public String getRegistrationNumber() {
|
||||
return registrationNumber;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.sealed.records;
|
||||
|
||||
public record Car(int numberOfSeats, String registrationNumber) implements Vehicle {
|
||||
|
||||
@Override
|
||||
public String getRegistrationNumber() {
|
||||
return registrationNumber;
|
||||
}
|
||||
|
||||
public int getNumberOfSeats() {
|
||||
return numberOfSeats;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.sealed.records;
|
||||
|
||||
public record Truck(int loadCapacity, String registrationNumber) implements Vehicle {
|
||||
|
||||
@Override
|
||||
public String getRegistrationNumber() {
|
||||
return registrationNumber;
|
||||
}
|
||||
|
||||
public int getLoadCapacity() {
|
||||
return loadCapacity;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.baeldung.sealed.records;
|
||||
|
||||
public sealed interface Vehicle permits Car, Truck {
|
||||
|
||||
String getRegistrationNumber();
|
||||
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.whatsnew.records;
|
||||
|
||||
/**
|
||||
* Java record with a header indicating 2 fields.
|
||||
*/
|
||||
public record Person(String name, int age) {
|
||||
/**
|
||||
* Public constructor that does some basic validation.
|
||||
*/
|
||||
public Person {
|
||||
if (age < 0) {
|
||||
throw new IllegalArgumentException("Age cannot be negative");
|
||||
}
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.whatsnew.sealedclasses;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
public non-sealed class Employee extends Person {
|
||||
public Date getHiredDate() {
|
||||
return new Date();
|
||||
}
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
package com.baeldung.whatsnew.sealedclasses;
|
||||
|
||||
public final class Manager extends Person {
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.whatsnew.sealedclasses;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
public sealed class Person permits Employee, Manager {
|
||||
/**
|
||||
* Demonstration of pattern matching for instanceof
|
||||
*
|
||||
* @param person A Person object
|
||||
* @return
|
||||
*/
|
||||
public static void patternMatchingDemo(Person person) {
|
||||
if(person instanceof Employee employee) {
|
||||
Date hiredDate = employee.getHiredDate();
|
||||
}
|
||||
|
||||
if(person instanceof Employee employee && employee.getHiredDate() != null) {
|
||||
Date hiredDate = employee.getHiredDate();
|
||||
}
|
||||
}
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
package com.baeldung.sealed.classes;
|
||||
|
||||
import org.assertj.core.api.Assertions;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.lang.constant.ClassDesc;
|
||||
|
||||
public class VehicleUnitTest {
|
||||
|
||||
private static Vehicle car;
|
||||
private static Vehicle truck;
|
||||
|
||||
@BeforeAll
|
||||
public static void createInstances() {
|
||||
car = new Car(5, "VZ500DA");
|
||||
truck = new Truck(19000, "VZ600TA");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCar_whenUsingReflectionAPI_thenSuperClassIsSealed() {
|
||||
Assertions.assertThat(car.getClass().isSealed()).isEqualTo(false);
|
||||
Assertions.assertThat(car.getClass().getSuperclass().isSealed()).isEqualTo(true);
|
||||
Assertions.assertThat(car.getClass().getSuperclass().permittedSubclasses())
|
||||
.contains(ClassDesc.of(car.getClass().getCanonicalName()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTruck_whenUsingReflectionAPI_thenSuperClassIsSealed() {
|
||||
Assertions.assertThat(truck.getClass().isSealed()).isEqualTo(false);
|
||||
Assertions.assertThat(truck.getClass().getSuperclass().isSealed()).isEqualTo(true);
|
||||
Assertions.assertThat(truck.getClass().getSuperclass().permittedSubclasses())
|
||||
.contains(ClassDesc.of(truck.getClass().getCanonicalName()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCar_whenGettingPropertyTraditionalWay_thenNumberOfSeatsPropertyIsReturned() {
|
||||
Assertions.assertThat(getPropertyTraditionalWay(car)).isEqualTo(5);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCar_whenGettingPropertyViaPatternMatching_thenNumberOfSeatsPropertyIsReturned() {
|
||||
Assertions.assertThat(getPropertyViaPatternMatching(car)).isEqualTo(5);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTruck_whenGettingPropertyTraditionalWay_thenLoadCapacityIsReturned() {
|
||||
Assertions.assertThat(getPropertyTraditionalWay(truck)).isEqualTo(19000);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTruck_whenGettingPropertyViaPatternMatching_thenLoadCapacityIsReturned() {
|
||||
Assertions.assertThat(getPropertyViaPatternMatching(truck)).isEqualTo(19000);
|
||||
}
|
||||
|
||||
private int getPropertyTraditionalWay(Vehicle vehicle) {
|
||||
if (vehicle instanceof Car) {
|
||||
return ((Car) vehicle).getNumberOfSeats();
|
||||
} else if (vehicle instanceof Truck) {
|
||||
return ((Truck) vehicle).getLoadCapacity();
|
||||
} else {
|
||||
throw new RuntimeException("Unknown instance of Vehicle");
|
||||
}
|
||||
}
|
||||
|
||||
private int getPropertyViaPatternMatching(Vehicle vehicle) {
|
||||
if (vehicle instanceof Car car) {
|
||||
return car.getNumberOfSeats();
|
||||
} else if (vehicle instanceof Truck truck) {
|
||||
return truck.getLoadCapacity();
|
||||
} else {
|
||||
throw new RuntimeException("Unknown instance of Vehicle");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
package com.baeldung.sealed.records;
|
||||
|
||||
import org.assertj.core.api.Assertions;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.lang.constant.ClassDesc;
|
||||
|
||||
public class VehicleUnitTest {
|
||||
|
||||
private static Vehicle car;
|
||||
private static Vehicle truck;
|
||||
|
||||
@BeforeAll
|
||||
public static void createInstances() {
|
||||
car = new Car(4, "VZ500DA");
|
||||
truck = new Truck(16000, "VZ600TA");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCar_whenUsingReflectionAPI_thenInterfaceIsSealed() {
|
||||
Assertions.assertThat(car.getClass().isSealed()).isEqualTo(false);
|
||||
Assertions.assertThat(car.getClass().getInterfaces()[0].isSealed()).isEqualTo(true);
|
||||
Assertions.assertThat(car.getClass().getInterfaces()[0].permittedSubclasses())
|
||||
.contains(ClassDesc.of(car.getClass().getCanonicalName()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTruck_whenUsingReflectionAPI_thenInterfaceIsSealed() {
|
||||
Assertions.assertThat(truck.getClass().isSealed()).isEqualTo(false);
|
||||
Assertions.assertThat(truck.getClass().getInterfaces()[0].isSealed()).isEqualTo(true);
|
||||
Assertions.assertThat(truck.getClass().getInterfaces()[0].permittedSubclasses())
|
||||
.contains(ClassDesc.of(truck.getClass().getCanonicalName()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCar_whenGettingPropertyTraditionalWay_thenNumberOfSeatsPropertyIsReturned() {
|
||||
Assertions.assertThat(getPropertyTraditionalWay(car)).isEqualTo(4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCar_whenGettingPropertyViaPatternMatching_thenNumberOfSeatsPropertyIsReturned() {
|
||||
Assertions.assertThat(getPropertyViaPatternMatching(car)).isEqualTo(4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTruck_whenGettingPropertyTraditionalWay_thenLoadCapacityIsReturned() {
|
||||
Assertions.assertThat(getPropertyTraditionalWay(truck)).isEqualTo(16000);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTruck_whenGettingPropertyViaPatternMatching_thenLoadCapacityIsReturned() {
|
||||
Assertions.assertThat(getPropertyViaPatternMatching(truck)).isEqualTo(16000);
|
||||
}
|
||||
|
||||
private int getPropertyTraditionalWay(Vehicle vehicle) {
|
||||
if (vehicle instanceof Car) {
|
||||
return ((Car) vehicle).getNumberOfSeats();
|
||||
} else if (vehicle instanceof Truck) {
|
||||
return ((Truck) vehicle).getLoadCapacity();
|
||||
} else {
|
||||
throw new RuntimeException("Unknown instance of Vehicle");
|
||||
}
|
||||
}
|
||||
|
||||
private int getPropertyViaPatternMatching(Vehicle vehicle) {
|
||||
if (vehicle instanceof Car car) {
|
||||
return car.getNumberOfSeats();
|
||||
} else if (vehicle instanceof Truck truck) {
|
||||
return truck.getLoadCapacity();
|
||||
} else {
|
||||
throw new RuntimeException("Unknown instance of Vehicle");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+1
-1
@@ -31,6 +31,6 @@ public class UseDateTimeFormatterUnitTest {
|
||||
public void givenALocalDate_whenFormattingWithStyleAndLocale_thenPass() {
|
||||
String result = subject.formatWithStyleAndLocale(localDateTime, FormatStyle.MEDIUM, Locale.UK);
|
||||
|
||||
assertThat(result).isEqualTo("25 Jan 2015, 06:30:00");
|
||||
assertThat(result).isEqualTo("25-Jan-2015 06:30:00");
|
||||
}
|
||||
}
|
||||
+4
-2
@@ -3,6 +3,7 @@ package com.baeldung.datetime;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.GregorianCalendar;
|
||||
@@ -24,10 +25,11 @@ public class UseToInstantUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenADate_whenConvertingToLocalDate_thenAsExpected() {
|
||||
Date givenDate = new Date(1465817690000L);
|
||||
LocalDateTime currentDateTime = LocalDateTime.now();
|
||||
Date givenDate = Date.from(currentDateTime.atZone(ZoneId.systemDefault()).toInstant());
|
||||
|
||||
LocalDateTime localDateTime = subject.convertDateToLocalDate(givenDate);
|
||||
|
||||
assertThat(localDateTime).isEqualTo("2016-06-13T13:34:50");
|
||||
assertThat(localDateTime).isEqualTo(currentDateTime);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -54,7 +54,7 @@ public class UseZonedDateTimeUnitTest {
|
||||
@Test
|
||||
public void givenAStringWithTimeZone_whenParsing_thenEqualsExpected() {
|
||||
ZonedDateTime resultFromString = zonedDateTime.getZonedDateTimeUsingParseMethod("2015-05-03T10:15:30+01:00[Europe/Paris]");
|
||||
ZonedDateTime resultFromLocalDateTime = ZonedDateTime.of(2015, 5, 3, 11, 15, 30, 0, ZoneId.of("Europe/Paris"));
|
||||
ZonedDateTime resultFromLocalDateTime = ZonedDateTime.of(2015, 5, 3, 10, 15, 30, 0, ZoneId.of("Europe/Paris"));
|
||||
|
||||
assertThat(resultFromString.getZone()).isEqualTo(ZoneId.of("Europe/Paris"));
|
||||
assertThat(resultFromLocalDateTime.getZone()).isEqualTo(ZoneId.of("Europe/Paris"));
|
||||
|
||||
+2
-2
@@ -19,12 +19,12 @@ public class StudentDbService implements StudentService {
|
||||
}
|
||||
|
||||
public Student update(Student student) {
|
||||
logger.log(Level.INFO, "Updating sutdent in DB...");
|
||||
logger.log(Level.INFO, "Updating student in DB...");
|
||||
return student;
|
||||
}
|
||||
|
||||
public String delete(String registrationId) {
|
||||
logger.log(Level.INFO, "Deleteing sutdent in DB...");
|
||||
logger.log(Level.INFO, "Deleting student in DB...");
|
||||
return registrationId;
|
||||
}
|
||||
}
|
||||
+6
-3
@@ -1,12 +1,15 @@
|
||||
package com.baeldung.modules.main;
|
||||
|
||||
import com.baeldung.modules.hello.HelloInterface;
|
||||
import com.baeldung.modules.hello.HelloModules;
|
||||
import java.util.ServiceLoader;
|
||||
|
||||
public class MainApp {
|
||||
public static void main(String[] args) {
|
||||
HelloModules.doSomething();
|
||||
|
||||
HelloModules module = new HelloModules();
|
||||
module.sayHello();
|
||||
|
||||
Iterable<HelloInterface> services = ServiceLoader.load(HelloInterface.class);
|
||||
HelloInterface service = services.iterator().next();
|
||||
service.sayHello();
|
||||
}
|
||||
}
|
||||
|
||||
+3
-10
@@ -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"));
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
@@ -13,3 +13,5 @@ This module contains articles about core Java features that have been introduced
|
||||
- [Java 9 Platform Logging API](https://www.baeldung.com/java-9-logging-api)
|
||||
- [Java 9 Reactive Streams](https://www.baeldung.com/java-9-reactive-streams)
|
||||
- [Multi-Release JAR Files with Maven](https://www.baeldung.com/maven-multi-release-jars)
|
||||
- [The Difference between RxJava API and the Java 9 Flow API](https://www.baeldung.com/rxjava-vs-java-flow-api)
|
||||
- [How to Get a Name of a Method Being Executed?](https://www.baeldung.com/java-name-of-executing-method)
|
||||
|
||||
@@ -9,3 +9,4 @@ This module contains articles about Java 9 core features
|
||||
- [Iterate Through a Range of Dates in Java](https://www.baeldung.com/java-iterate-date-range)
|
||||
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
|
||||
- [Immutable ArrayList in Java](https://www.baeldung.com/java-immutable-list)
|
||||
- [Easy Ways to Write a Java InputStream to an OutputStream](https://www.baeldung.com/java-inputstream-to-outputstream)
|
||||
|
||||
@@ -44,6 +44,16 @@
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>${commons-collections4.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
<version>${commons-io.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
@@ -77,6 +87,7 @@
|
||||
<maven.compiler.target>1.9</maven.compiler.target>
|
||||
<guava.version>25.1-jre</guava.version>
|
||||
<commons-collections4.version>4.1</commons-collections4.version>
|
||||
<commons-collections3.version>3.2.2</commons-collections3.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
+1
-1
@@ -17,7 +17,7 @@ import org.junit.Test;
|
||||
/**
|
||||
* Test case for the {@link MethodHandles} API
|
||||
*/
|
||||
public class MethodHandlesTest {
|
||||
public class MethodHandlesUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenConcatMethodHandle_whenInvoked_thenCorrectlyConcatenated() throws Throwable {
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.annotations;
|
||||
|
||||
import javax.annotation.Generated;
|
||||
|
||||
@RetentionAnnotation
|
||||
@Generated("Available only on source code")
|
||||
public class AnnotatedClass {
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.annotations;
|
||||
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
import static java.lang.annotation.ElementType.TYPE;
|
||||
|
||||
@Target(TYPE)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface RetentionAnnotation {
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.annotations;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.lang.annotation.Annotation;
|
||||
|
||||
import static org.hamcrest.core.Is.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
public class AnnotatedClassUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenAnnotationRetentionPolicyRuntime_shouldAccess() {
|
||||
AnnotatedClass anAnnotatedClass = new AnnotatedClass();
|
||||
Annotation[] annotations = anAnnotatedClass.getClass().getAnnotations();
|
||||
assertThat(annotations.length, is(1));
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -5,7 +5,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class JsonSerializerUnitTest {
|
||||
public class ObjectToJsonConverterUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenObjectNotSerializedThenExceptionThrown() throws JsonSerializationException {
|
||||
@@ -5,4 +5,6 @@ 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)
|
||||
|
||||
@@ -17,16 +17,18 @@
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>${jmh.version}</version>
|
||||
<version>${jmh-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${jmh.version}</version>
|
||||
<version>${jmh-generator.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>3.19.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<jmh.version>1.19</jmh.version>
|
||||
</properties>
|
||||
</project>
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.array.arraystoreexception;
|
||||
|
||||
public class ArrayStoreExampleCE {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
//String array[] = new String[5]; //This will lead to compile-time error at line-8 when uncommented
|
||||
//array[0] = 2;
|
||||
}
|
||||
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.array.arraystoreexception;
|
||||
|
||||
public class ArrayStoreExceptionExample {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
try {
|
||||
Object array[] = new String[5];
|
||||
array[0] = 2;
|
||||
} catch (ArrayStoreException e) {
|
||||
// handle the exception
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.genericarrays;
|
||||
|
||||
import java.lang.reflect.Array;
|
||||
|
||||
public class MyStack<E> {
|
||||
private E[] elements;
|
||||
private int size = 0;
|
||||
|
||||
public MyStack(Class<E> clazz, int capacity) {
|
||||
elements = (E[]) Array.newInstance(clazz, capacity);
|
||||
}
|
||||
|
||||
public void push(E item) {
|
||||
if (size == elements.length) {
|
||||
throw new RuntimeException();
|
||||
}
|
||||
elements[size++] = item;
|
||||
}
|
||||
|
||||
public E pop() {
|
||||
if (size == 0) {
|
||||
throw new RuntimeException();
|
||||
}
|
||||
return elements[--size];
|
||||
}
|
||||
|
||||
public E[] getAllElements() {
|
||||
return elements;
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.genericarrays;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class ListToArrayUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenListOfItems_whenToArray_thenReturnArrayOfItems() {
|
||||
List<String> items = new LinkedList<>();
|
||||
items.add("first item");
|
||||
items.add("second item");
|
||||
|
||||
String[] itemsAsArray = items.toArray(new String[0]);
|
||||
|
||||
assertEquals("first item", itemsAsArray[0]);
|
||||
assertEquals("second item", itemsAsArray[1]);
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.genericarrays;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class MyStackUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenStackWithTwoItems_whenPop_thenReturnLastAdded() {
|
||||
MyStack<String> myStack = new MyStack<>(String.class, 2);
|
||||
myStack.push("hello");
|
||||
myStack.push("example");
|
||||
|
||||
assertEquals("example", myStack.pop());
|
||||
}
|
||||
|
||||
@Test (expected = RuntimeException.class)
|
||||
public void givenStackWithFixedCapacity_whenExceedCapacity_thenThrowException() {
|
||||
MyStack<Integer> myStack = new MyStack<>(Integer.class, 2);
|
||||
myStack.push(100);
|
||||
myStack.push(200);
|
||||
myStack.push(300);
|
||||
}
|
||||
|
||||
@Test(expected = RuntimeException.class)
|
||||
public void givenStack_whenPopOnEmptyStack_thenThrowException() {
|
||||
MyStack<Integer> myStack = new MyStack<>(Integer.class, 1);
|
||||
myStack.push(100);
|
||||
myStack.pop();
|
||||
myStack.pop();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStackWithItems_whenGetAllElements_thenSizeShouldEqualTotal() {
|
||||
MyStack<String> myStack = new MyStack<>(String.class, 2);
|
||||
myStack.push("hello");
|
||||
myStack.push("example");
|
||||
|
||||
String[] items = myStack.getAllElements();
|
||||
|
||||
assertEquals(2, items.length);
|
||||
}
|
||||
}
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
package com.baeldung.genericarrays;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.function.IntFunction;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static java.util.Collections.singletonList;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
public class StreamToArrayUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenAStream_thenCanGetArrayOfObject() {
|
||||
Object[] strings = Stream.of("A", "AAA", "B", "AAB", "C")
|
||||
.filter(string -> string.startsWith("A"))
|
||||
.toArray();
|
||||
|
||||
assertThat(strings).containsExactly("A", "AAA", "AAB");
|
||||
assertThat(strings).isNotInstanceOf(String[].class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAStream_thenCanGetArrayOfString() {
|
||||
String[] strings = Stream.of("A", "AAA", "B", "AAB", "C")
|
||||
.filter(string -> string.startsWith("A"))
|
||||
.toArray(String[]::new);
|
||||
|
||||
assertThat(strings).containsExactly("A", "AAA", "AAB");
|
||||
assertThat(strings).isInstanceOf(String[].class);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test
|
||||
public void givenAStream_whenConvertToOptional_thenCanGetArrayOfOptional() {
|
||||
Stream<Optional<String>> stream = Stream.of("A", "AAA", "B", "AAB", "C")
|
||||
.filter(string -> string.startsWith("A"))
|
||||
.map(Optional::of);
|
||||
Optional<String>[] strings = stream
|
||||
.toArray(Optional[]::new);
|
||||
|
||||
assertThat(strings).containsExactly(Optional.of("A"),
|
||||
Optional.of("AAA"),
|
||||
Optional.of("AAB"));
|
||||
assertThat(strings).isInstanceOf(Optional[].class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAStream_whenConvertToOptional_thenCanGetArrayOfOptionalWithHelper() {
|
||||
Optional<String>[] strings = Stream.of("A", "AAA", "B", "AAB", "C")
|
||||
.filter(string -> string.startsWith("A"))
|
||||
.map(Optional::of)
|
||||
.toArray(genericArray(Optional[]::new));
|
||||
|
||||
assertThat(strings).containsExactly(Optional.of("A"),
|
||||
Optional.of("AAA"),
|
||||
Optional.of("AAB"));
|
||||
assertThat(strings).isInstanceOf(Optional[].class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenInvalidUseOfGenericArray_thenIllegalCast() {
|
||||
assertThatThrownBy(() -> {
|
||||
ArrayList<String>[] lists = Stream.of(singletonList("A"))
|
||||
.toArray(genericArray(List[]::new));
|
||||
}).isInstanceOf(ClassCastException.class);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static <T, R extends T> IntFunction<R[]> genericArray(IntFunction<T[]> arrayCreator) {
|
||||
return size -> (R[])arrayCreator.apply(size);
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,9 @@
|
||||
This module contains articles about advanced operations on arrays in Java. They assume some background knowledge with arrays in Java.
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- [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)
|
||||
- [Comparing Arrays in Java](https://www.baeldung.com/java-comparing-arrays)
|
||||
|
||||
@@ -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>
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.arraycompare;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public class Plane {
|
||||
|
||||
private final String name;
|
||||
|
||||
private final String model;
|
||||
|
||||
public Plane(String name, String model) {
|
||||
|
||||
this.name = name;
|
||||
this.model = model;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public String getModel() {
|
||||
return model;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o)
|
||||
return true;
|
||||
if (o == null || getClass() != o.getClass())
|
||||
return false;
|
||||
Plane plane = (Plane) o;
|
||||
return Objects.equals(name, plane.name) && Objects.equals(model, plane.model);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(name, model);
|
||||
}
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
package com.baeldung.arrayconcat;
|
||||
|
||||
import java.lang.reflect.Array;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class ArrayConcatUtil {
|
||||
private ArrayConcatUtil() {}
|
||||
|
||||
static <T> T[] concatWithCollection(T[] array1, T[] array2) {
|
||||
List<T> resultList = new ArrayList<>(array1.length + array2.length);
|
||||
Collections.addAll(resultList, array1);
|
||||
Collections.addAll(resultList, array2);
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
//the type cast is safe as the array1 has the type T[]
|
||||
T[] resultArray = (T[]) Array.newInstance(array1.getClass().getComponentType(), 0);
|
||||
return resultList.toArray(resultArray);
|
||||
}
|
||||
|
||||
static <T> T[] concatWithArrayCopy(T[] array1, T[] array2) {
|
||||
T[] result = Arrays.copyOf(array1, array1.length + array2.length);
|
||||
System.arraycopy(array2, 0, result, array1.length, array2.length);
|
||||
return result;
|
||||
}
|
||||
|
||||
static <T> T concatWithCopy2(T array1, T array2) {
|
||||
if (!array1.getClass().isArray() || !array2.getClass().isArray()) {
|
||||
throw new IllegalArgumentException("Only arrays are accepted.");
|
||||
}
|
||||
|
||||
Class<?> compType1 = array1.getClass().getComponentType();
|
||||
Class<?> compType2 = array2.getClass().getComponentType();
|
||||
|
||||
if (!compType1.equals(compType2)) {
|
||||
throw new IllegalArgumentException("Two arrays have different types.");
|
||||
}
|
||||
|
||||
int len1 = Array.getLength(array1);
|
||||
int len2 = Array.getLength(array2);
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
//the cast is safe due to the previous checks
|
||||
T result = (T) Array.newInstance(compType1, len1 + len2);
|
||||
|
||||
System.arraycopy(array1, 0, result, 0, len1);
|
||||
System.arraycopy(array2, 0, result, len1, len2);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
static <T> T[] concatWithStream(T[] array1, T[] array2) {
|
||||
return Stream.concat(Arrays.stream(array1), Arrays.stream(array2))
|
||||
.toArray(size -> (T[]) Array.newInstance(array1.getClass().getComponentType(), size));
|
||||
}
|
||||
|
||||
static int[] concatIntArraysWithIntStream(int[] array1, int[] array2) {
|
||||
return IntStream.concat(Arrays.stream(array1), Arrays.stream(array2)).toArray();
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.arraycompare;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class DeepEqualsCompareUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenSameContents_whenDeepEquals_thenTrue() {
|
||||
final Plane[][] planes1 = new Plane[][] { new Plane[] { new Plane("Plane 1", "A320") },
|
||||
new Plane[] { new Plane("Plane 2", "B738") } };
|
||||
final Plane[][] planes2 = new Plane[][] { new Plane[] { new Plane("Plane 1", "A320") },
|
||||
new Plane[] { new Plane("Plane 2", "B738") } };
|
||||
|
||||
assertThat(Arrays.deepEquals(planes1, planes2)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSameContentsWithDifferentOrder_whenDeepEquals_thenFalse() {
|
||||
final Plane[][] planes1 = new Plane[][] { new Plane[] { new Plane("Plane 1", "A320") },
|
||||
new Plane[] { new Plane("Plane 2", "B738") } };
|
||||
final Plane[][] planes2 = new Plane[][] { new Plane[] { new Plane("Plane 2", "B738") },
|
||||
new Plane[] { new Plane("Plane 1", "A320") } };
|
||||
|
||||
assertThat(Arrays.deepEquals(planes1, planes2)).isFalse();
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.arraycompare;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class EqualsCompareUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenSameContents_whenEquals_thenTrue() {
|
||||
final String[] planes1 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" };
|
||||
final String[] planes2 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" };
|
||||
|
||||
assertThat(Arrays.equals(planes1, planes2)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSameContentsDifferentOrder_whenEquals_thenFalse() {
|
||||
final String[] planes1 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" };
|
||||
final String[] planes2 = new String[] { "B738", "A320", "A321", "A319", "B77W", "B737", "A333", "A332" };
|
||||
|
||||
assertThat(Arrays.equals(planes1, planes2)).isFalse();
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.arraycompare;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class LengthsCompareUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenSameContent_whenSizeCompare_thenTrue() {
|
||||
final String[] planes1 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" };
|
||||
final Integer[] quantities = new Integer[] { 10, 12, 34, 45, 12, 43, 5, 2 };
|
||||
|
||||
assertThat(planes1).hasSize(8);
|
||||
assertThat(quantities).hasSize(8);
|
||||
}
|
||||
}
|
||||
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package com.baeldung.arraycompare;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class OrderCompareUnitTest {
|
||||
@Test
|
||||
public void givenSameContentDifferentOrder_whenSortedAndDeepEquals_thenTrue() {
|
||||
final Plane[][] planes1 = new Plane[][] {
|
||||
new Plane[] { new Plane("Plane 1", "A320"), new Plane("Plane 2", "B738") } };
|
||||
final Plane[][] planes2 = new Plane[][] {
|
||||
new Plane[] { new Plane("Plane 2", "B738"), new Plane("Plane 1", "A320") } };
|
||||
|
||||
Comparator<Plane> planeComparator = (o1, o2) -> {
|
||||
if (o1.getName()
|
||||
.equals(o2.getName())) {
|
||||
return o2.getModel()
|
||||
.compareTo(o1.getModel());
|
||||
}
|
||||
return o2.getName()
|
||||
.compareTo(o1.getName());
|
||||
};
|
||||
Arrays.sort(planes1[0], planeComparator);
|
||||
Arrays.sort(planes2[0], planeComparator);
|
||||
|
||||
assertThat(Arrays.deepEquals(planes1, planes2)).isTrue();
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.arraycompare;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class ReferenceCompareUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenSameReferences_whenSame_thenTrue() {
|
||||
final String[] planes1 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" };
|
||||
final String[] planes2 = planes1;
|
||||
|
||||
assertThat(planes1).isSameAs(planes2);
|
||||
|
||||
planes2[0] = "747";
|
||||
|
||||
assertThat(planes1).isSameAs(planes2);
|
||||
assertThat(planes2[0]).isEqualTo("747");
|
||||
assertThat(planes1[0]).isEqualTo("747");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSameContentDifferentReferences_whenSame_thenFalse() {
|
||||
final String[] planes1 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" };
|
||||
final String[] planes2 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" };
|
||||
|
||||
assertThat(planes1).isNotSameAs(planes2);
|
||||
}
|
||||
}
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
package com.baeldung.arrayconcat;
|
||||
|
||||
|
||||
import com.google.common.collect.ObjectArrays;
|
||||
import com.google.common.primitives.Ints;
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.fail;
|
||||
|
||||
public class ArrayConcatUtilUnitTest {
|
||||
private final String[] strArray1 = { "element 1", "element 2", "element 3" };
|
||||
private final String[] strArray2 = { "element 4", "element 5" };
|
||||
private final String[] expectedStringArray = { "element 1", "element 2", "element 3", "element 4", "element 5" };
|
||||
|
||||
private final int[] intArray1 = { 0, 1, 2, 3 };
|
||||
private final int[] intArray2 = { 4, 5, 6, 7 };
|
||||
private final int[] expectedIntArray = { 0, 1, 2, 3, 4, 5, 6, 7 };
|
||||
|
||||
@Test
|
||||
public void givenTwoStringArrays_whenConcatWithList_thenGetExpectedResult() {
|
||||
String[] result = ArrayConcatUtil.concatWithCollection(strArray1, strArray2);
|
||||
assertThat(result).isEqualTo(expectedStringArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoStringArrays_whenConcatWithCopy_thenGetExpectedResult() {
|
||||
String[] result = ArrayConcatUtil.concatWithArrayCopy(strArray1, strArray2);
|
||||
assertThat(result).isEqualTo(expectedStringArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoStrings_whenConcatWithCopy2_thenGetException() {
|
||||
String exMsg = "Only arrays are accepted.";
|
||||
try {
|
||||
ArrayConcatUtil.concatWithCopy2("String Nr. 1", "String Nr. 2");
|
||||
fail(String.format("IllegalArgumentException with message:'%s' should be thrown. But it didn't", exMsg));
|
||||
} catch (IllegalArgumentException e) {
|
||||
assertThat(e).hasMessage(exMsg);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoArraysInDifferentTypes_whenConcatWithCopy2_thenGetException() {
|
||||
String[] strArray = new String[] { "test 1", "test 2" };
|
||||
Integer[] integerArray = new Integer[] { 7, 11 };
|
||||
String exMsg = "Two arrays have different types.";
|
||||
|
||||
try {
|
||||
ArrayConcatUtil.concatWithCopy2(strArray, integerArray);
|
||||
fail(String.format("IllegalArgumentException with message:'%s' should be thrown. But it didn't", exMsg));
|
||||
} catch (IllegalArgumentException e) {
|
||||
assertThat(e).hasMessage(exMsg);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoArrays_whenConcatWithCopy2_thenGetExpectedResult() {
|
||||
String[] result = ArrayConcatUtil.concatWithCopy2(strArray1, strArray2);
|
||||
assertThat(result).isEqualTo(expectedStringArray);
|
||||
|
||||
int[] intResult = ArrayConcatUtil.concatWithCopy2(intArray1, intArray2);
|
||||
assertThat(intResult).isEqualTo(expectedIntArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoStringArrays_whenConcatWithStream_thenGetExpectedResult() {
|
||||
String[] result = ArrayConcatUtil.concatWithStream(strArray1, strArray2);
|
||||
assertThat(result).isEqualTo(expectedStringArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoIntArrays_whenConcatWithIntStream_thenGetExpectedResult() {
|
||||
int[] intResult = ArrayConcatUtil.concatIntArraysWithIntStream(intArray1, intArray2);
|
||||
assertThat(intResult).isEqualTo(expectedIntArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoArrays_whenConcatWithCommonsLang_thenGetExpectedResult() {
|
||||
String[] result = ArrayUtils.addAll(strArray1, strArray2);
|
||||
assertThat(result).isEqualTo(expectedStringArray);
|
||||
|
||||
int[] intResult = ArrayUtils.addAll(intArray1, intArray2);
|
||||
assertThat(intResult).isEqualTo(expectedIntArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoStringArrays_whenConcatWithGuava_thenGetExpectedResult() {
|
||||
String[] result = ObjectArrays.concat(strArray1, strArray2, String.class);
|
||||
assertThat(result).isEqualTo(expectedStringArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoIntArrays_whenConcatWithGuava_thenGetExpectedResult() {
|
||||
int[] intResult = Ints.concat(intArray1, intArray2);
|
||||
assertThat(intResult).isEqualTo(expectedIntArray);
|
||||
}
|
||||
}
|
||||
@@ -24,12 +24,12 @@
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>${jmh.version}</version>
|
||||
<version>${jmh-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${jmh.version}</version>
|
||||
<version>${jmh-generator.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
@@ -68,11 +68,6 @@
|
||||
|
||||
<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>
|
||||
@@ -31,12 +31,12 @@
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>${jmh.version}</version>
|
||||
<version>${jmh-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${jmh.version}</version>
|
||||
<version>${jmh-generator.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Testing -->
|
||||
@@ -76,12 +76,7 @@
|
||||
|
||||
<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>
|
||||
@@ -0,0 +1,6 @@
|
||||
## Core Java Character
|
||||
|
||||
This module contains articles about Java Character Class
|
||||
|
||||
### Relevant Articles:
|
||||
- [Character#isAlphabetic vs. Character#isLetter](https://www.baeldung.com/java-character-isletter-isalphabetic)
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user