Merge branch 'master' of https://github.com/Maiklins/tutorials into JAVA-7244-Review_log_statements_for_projects
Conflicts: algorithms-searching/src/test/java/com/baeldung/algorithms/quadtree/QuadTreeSearchUnitTest.java
This commit is contained in:
@@ -8,3 +8,4 @@ This module contains articles about Java 11 core features
|
||||
- [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)
|
||||
- [Getting the Java Version at Runtime](https://www.baeldung.com/get-java-version-runtime)
|
||||
- [Invoking a SOAP Web Service in Java](https://www.baeldung.com/java-soap-web-service)
|
||||
|
||||
@@ -35,19 +35,19 @@
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<version>${junit.jupiter.version}</version>
|
||||
<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>
|
||||
<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>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@@ -106,7 +106,6 @@
|
||||
<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>
|
||||
<commons-lang3.version>3.12.0</commons-lang3.version>
|
||||
|
||||
@@ -1,60 +1,60 @@
|
||||
<?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-12</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-12</name>
|
||||
<packaging>jar</packaging>
|
||||
<url>http://maven.apache.org</url>
|
||||
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-12</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-12</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>
|
||||
</parent>
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
<version>2.11.0</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
<version>2.11.0</version>
|
||||
</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>
|
||||
<compilerArgs>--enable-preview</compilerArgs>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<argLine>--enable-preview</argLine>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<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>
|
||||
<compilerArgs>--enable-preview</compilerArgs>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<argLine>--enable-preview</argLine>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source.version>12</maven.compiler.source.version>
|
||||
<maven.compiler.target.version>12</maven.compiler.target.version>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
</properties>
|
||||
<properties>
|
||||
<maven.compiler.source.version>12</maven.compiler.source.version>
|
||||
<maven.compiler.target.version>12</maven.compiler.target.version>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -14,7 +14,7 @@
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../</relativePath>
|
||||
</parent>
|
||||
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
@@ -35,7 +35,7 @@
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
### Relevant articles:
|
||||
|
||||
- [Collect a Java Stream to an Immutable Collection](https://www.baeldung.com/java-stream-immutable-collection)
|
||||
- [Guide to mapMulti in Stream API](https://www.baeldung.com/java-mapmulti)
|
||||
- [Collecting Stream Elements into a List in Java](https://www.baeldung.com/java-stream-to-list-collecting)
|
||||
- [New Features in Java 16](https://www.baeldung.com/java-16-new-features)
|
||||
- [Guide to Java 8 groupingBy Collector](https://www.baeldung.com/java-groupingby-collector)
|
||||
|
||||
@@ -1,53 +1,86 @@
|
||||
<?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-16</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-16</name>
|
||||
<packaging>jar</packaging>
|
||||
<url>http://maven.apache.org</url>
|
||||
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-16</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-16</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>
|
||||
</parent>
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>3.12.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>3.12.0</version>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<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>${maven.compiler.source.version}</source>
|
||||
<target>${maven.compiler.target.version}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${surefire.plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${maven.compiler.source.version}</source>
|
||||
<target>${maven.compiler.target.version}</target>
|
||||
<argLine>--enable-preview</argLine>
|
||||
<forkCount>1</forkCount>
|
||||
</configuration>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.maven.surefire</groupId>
|
||||
<artifactId>surefire-api</artifactId>
|
||||
<version>${surefire.plugin.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source.version>16</maven.compiler.source.version>
|
||||
<maven.compiler.target.version>16</maven.compiler.target.version>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
</properties>
|
||||
<properties>
|
||||
<maven.compiler.source.version>16</maven.compiler.source.version>
|
||||
<maven.compiler.target.version>16</maven.compiler.target.version>
|
||||
<maven.compiler.release>16</maven.compiler.release>
|
||||
<maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
|
||||
<surefire.plugin.version>3.0.0-M5</surefire.plugin.version>
|
||||
<assertj.version>3.17.2</assertj.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.baeldung.features;
|
||||
|
||||
interface HelloWorld {
|
||||
default String hello() {
|
||||
return "world";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.features;
|
||||
|
||||
import com.baeldung.features.record.Book;
|
||||
|
||||
public class OuterClass {
|
||||
class InnerClass {
|
||||
Book book = new Book("Title", "author", "isbn");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.features;
|
||||
|
||||
import jdk.incubator.vector.IntVector;
|
||||
|
||||
public class VectorExample {
|
||||
public int[] scalarComputation(int[] a, int[] b) {
|
||||
var c = new int[a.length];
|
||||
for (int i = 0; i < a.length; i++) {
|
||||
c[i] = a[i] * b[i];
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
public int[] vectorComputation(int[] a, int[] b) {
|
||||
var c = new int[a.length];
|
||||
|
||||
var vectorA = IntVector.fromArray(IntVector.SPECIES_128, a, 0);
|
||||
var vectorB = IntVector.fromArray(IntVector.SPECIES_128, b, 0);
|
||||
var vectorC = vectorA.mul(vectorB);
|
||||
vectorC.intoArray(c, 0);
|
||||
return c;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.features.model;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public final class Book {
|
||||
private final String title;
|
||||
private final String author;
|
||||
private final String isbn;
|
||||
|
||||
public Book(String title, String author, String isbn) {
|
||||
this.title = title;
|
||||
this.author = author;
|
||||
this.isbn = isbn;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public String getAuthor() {
|
||||
return author;
|
||||
}
|
||||
|
||||
public String getIsbn() {
|
||||
return isbn;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
Book book = (Book) o;
|
||||
return Objects.equals(title, book.title) && Objects.equals(author, book.author) && Objects.equals(isbn, book.isbn);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(title, author, isbn);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package com.baeldung.features.record;
|
||||
|
||||
public record Book(String title, String author, String isbn) {
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
package com.baeldung.features.sealed;
|
||||
|
||||
public sealed interface JungleAnimal permits Monkey, Snake {
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package com.baeldung.features.sealed;
|
||||
|
||||
public final class Monkey implements JungleAnimal {
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.features.sealed;
|
||||
|
||||
public class Sealed {
|
||||
public static void main(String... args) {
|
||||
JungleAnimal j = new Monkey();
|
||||
|
||||
if (j instanceof Monkey m) {
|
||||
// do logic
|
||||
} else if (j instanceof Snake s) {
|
||||
// do logic
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package com.baeldung.features.sealed;
|
||||
|
||||
public non-sealed class Snake implements JungleAnimal {
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
module core.java {
|
||||
requires jdk.incubator.vector;
|
||||
requires org.apache.commons.lang3;
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.features;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.LocalTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class DayPeriodSupportUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenASpecificTime_whenFormattingUsingTheBSymbol_thenExpectVerbosePeriodOfDay() {
|
||||
LocalTime date = LocalTime.parse("15:25:08.690791");
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("h B");
|
||||
assertThat(date.format(formatter)).isEqualTo("3 in the afternoon");
|
||||
|
||||
formatter = DateTimeFormatter.ofPattern("h BBBB");
|
||||
assertThat(date.format(formatter)).isEqualTo("3 in the afternoon");
|
||||
|
||||
formatter = DateTimeFormatter.ofPattern("h BBBBB");
|
||||
assertThat(date.format(formatter)).isEqualTo("3 in the afternoon");
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package com.baeldung.features;
|
||||
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.lang.reflect.InvocationHandler;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Proxy;
|
||||
|
||||
import static java.lang.ClassLoader.getSystemClassLoader;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class HelloWorldUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenAnInterfaceWithDefaulMethod_whenCreatingProxyInstance_thenCanInvokeDefaultMethod() throws Exception {
|
||||
Object proxy = Proxy.newProxyInstance(getSystemClassLoader(), new Class<?>[] { HelloWorld.class },
|
||||
(prox, method, args) -> {
|
||||
if (method.isDefault()) {
|
||||
return InvocationHandler.invokeDefault(prox, method, args);
|
||||
}
|
||||
return method.invoke(prox, args);
|
||||
}
|
||||
);
|
||||
Method method = proxy.getClass().getMethod("hello");
|
||||
assertThat(method.invoke(proxy)).isEqualTo("world");
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.features;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class InstanceOfPatternMatchingUnitTest {
|
||||
|
||||
@Test
|
||||
void givenTheNewPatternMatchingAbility_whenComparingAgainstTheTradiationalApproach_thenBothVariablesAreEqual() {
|
||||
Object obj = "TEST";
|
||||
|
||||
if (obj instanceof String a) {
|
||||
String b = (String) obj;
|
||||
assertThat(a).isEqualTo(b);
|
||||
}
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.features;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class StreamToListUnitTest {
|
||||
|
||||
@Test
|
||||
void givenAStream_whenCreatingANewListFromStream_thenCollectorsOrInbuiltFunctionAreEquivalent() {
|
||||
List<String> integersAsString = Arrays.asList("1", "2", "3");
|
||||
List<Integer> ints = integersAsString.stream().map(Integer::parseInt).collect(Collectors.toList());
|
||||
List<Integer> intsEquivalent = integersAsString.stream().map(Integer::parseInt).toList();
|
||||
assertThat(ints).isEqualTo(intsEquivalent);
|
||||
}
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.features;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
|
||||
class VectorExampleUnitTest {
|
||||
|
||||
@Test
|
||||
void givenAScalarComputation_whenCalculatingUsingVectorAPI_thenResultIsSameAsPreviousMethodOfComputation() {
|
||||
VectorExample objectUnderTest = new VectorExample();
|
||||
|
||||
int[] a = {1, 2, 3, 4};
|
||||
int[] b = {5, 6, 7, 8};
|
||||
|
||||
int[] result = objectUnderTest.scalarComputation(a, b);
|
||||
int[] result2 = objectUnderTest.vectorComputation(a, b);
|
||||
|
||||
assertArrayEquals(result, result2);
|
||||
}
|
||||
}
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
package com.baeldung.streams;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class StreamToListComparisonWithCollectorsToListUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenAddingtoCollectToList_thenSuccess() {
|
||||
|
||||
List<String> result = Stream.of(Locale.getISOCountries())
|
||||
.collect(Collectors.toList());
|
||||
|
||||
Assertions.assertDoesNotThrow(() -> {
|
||||
result.add("test");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSortingtoCollectToList_thenSuccess() {
|
||||
|
||||
List<String> result = Stream.of(Locale.getISOCountries())
|
||||
.collect(Collectors.toList());
|
||||
|
||||
Assertions.assertDoesNotThrow(() -> {
|
||||
result.sort(String::compareToIgnoreCase);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAddingCollectUnmodifiableToList_thenException() {
|
||||
|
||||
List<String> result = Stream.of(Locale.getISOCountries())
|
||||
.collect(Collectors.toUnmodifiableList());
|
||||
|
||||
Assertions.assertThrows(UnsupportedOperationException.class, () -> {
|
||||
result.add("test");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSortingCollectUnmodifiableToList_thenSortException() {
|
||||
|
||||
List<String> result = Stream.of(Locale.getISOCountries())
|
||||
.collect(Collectors.toUnmodifiableList());
|
||||
|
||||
Assertions.assertThrows(UnsupportedOperationException.class, () -> {
|
||||
result.sort(String::compareToIgnoreCase);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAddingStreamToList_thenException() {
|
||||
|
||||
List<String> result = Stream.of(Locale.getISOCountries())
|
||||
.toList();
|
||||
|
||||
Assertions.assertThrows(UnsupportedOperationException.class, () -> {
|
||||
result.add("test");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSortingStreamToList_thenException() {
|
||||
|
||||
List<String> result = Stream.of(Locale.getISOCountries())
|
||||
.toList();
|
||||
|
||||
Assertions.assertThrows(UnsupportedOperationException.class, () -> {
|
||||
result.sort(String::compareToIgnoreCase);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenComparingStreamToList_withCollectToList_thenEqual() {
|
||||
|
||||
List<String> streamToList = Stream.of(Locale.getISOCountries())
|
||||
.toList();
|
||||
List<String> collectToList = Stream.of(Locale.getISOCountries())
|
||||
.collect(Collectors.toList());
|
||||
|
||||
Assertions.assertEquals(streamToList, collectToList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenComparingStreamToList_withUnmodifiedCollectToList_thenEqual() {
|
||||
|
||||
List<String> streamToList = Stream.of(Locale.getISOCountries())
|
||||
.toList();
|
||||
List<String> collectToUnmodifiableList = Stream.of(Locale.getISOCountries())
|
||||
.collect(Collectors.toUnmodifiableList());
|
||||
|
||||
Assertions.assertEquals(streamToList, collectToUnmodifiableList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNullCollectorsToList_thenSuccess() {
|
||||
|
||||
Assertions.assertDoesNotThrow(() -> {
|
||||
Stream.of(null, null)
|
||||
.collect(Collectors.toList());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNullCollectorsUnmodifiableToList_thenException() {
|
||||
|
||||
Assertions.assertThrows(NullPointerException.class, () -> {
|
||||
Stream.of(null, null)
|
||||
.collect(Collectors.toUnmodifiableList());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNullStreamToList_thenSuccess() {
|
||||
|
||||
Assertions.assertDoesNotThrow(() -> {
|
||||
Stream.of(null, null)
|
||||
.toList();
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
### Relevant articles:
|
||||
|
||||
- [Pattern Matching for Switch](https://www.baeldung.com/java-switch-pattern-matching)
|
||||
@@ -0,0 +1,81 @@
|
||||
<?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-17</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-17</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>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<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>${maven.compiler.source.version}</source>
|
||||
<target>${maven.compiler.target.version}</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>
|
||||
<forkCount>1</forkCount>
|
||||
</configuration>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.maven.surefire</groupId>
|
||||
<artifactId>surefire-api</artifactId>
|
||||
<version>${surefire.plugin.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source.version>17</maven.compiler.source.version>
|
||||
<maven.compiler.target.version>17</maven.compiler.target.version>
|
||||
<maven.compiler.release>17</maven.compiler.release>
|
||||
<maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
|
||||
<surefire.plugin.version>3.0.0-M5</surefire.plugin.version>
|
||||
<assertj.version>3.17.2</assertj.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.switchpatterns;
|
||||
|
||||
public class GuardedPatterns {
|
||||
|
||||
static double getDoubleValueUsingIf(Object o) {
|
||||
return switch (o) {
|
||||
case String s -> {
|
||||
if (s.length() > 0) {
|
||||
yield Double.parseDouble(s);
|
||||
} else {
|
||||
yield 0d;
|
||||
}
|
||||
}
|
||||
default -> 0d;
|
||||
};
|
||||
}
|
||||
|
||||
static double getDoubleValueUsingGuardedPatterns(Object o) {
|
||||
return switch (o) {
|
||||
case String s && s.length() > 0 -> Double.parseDouble(s);
|
||||
default -> 0d;
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.switchpatterns;
|
||||
|
||||
public class HandlingNullValues {
|
||||
|
||||
static double getDoubleUsingSwitchNullCase(Object o) {
|
||||
return switch (o) {
|
||||
case String s -> Double.parseDouble(s);
|
||||
case null -> 0d;
|
||||
default -> 0d;
|
||||
};
|
||||
}
|
||||
|
||||
static double getDoubleUsingSwitchTotalType(Object o) {
|
||||
return switch (o) {
|
||||
case String s -> Double.parseDouble(s);
|
||||
case Object ob -> 0d;
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.switchpatterns;
|
||||
|
||||
public class ParenthesizedPatterns {
|
||||
|
||||
static double getDoubleValueUsingIf(Object o) {
|
||||
return switch (o) {
|
||||
case String s -> {
|
||||
if (s.length() > 0) {
|
||||
if (s.contains("#") || s.contains("@")) {
|
||||
yield 0d;
|
||||
} else {
|
||||
yield Double.parseDouble(s);
|
||||
}
|
||||
} else {
|
||||
yield 0d;
|
||||
}
|
||||
}
|
||||
default -> 0d;
|
||||
};
|
||||
}
|
||||
|
||||
static double getDoubleValueUsingParenthesizedPatterns(Object o) {
|
||||
return switch (o) {
|
||||
case String s && s.length() > 0 && !(s.contains("#") || s.contains("@")) -> Double.parseDouble(s);
|
||||
default -> 0d;
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.switchpatterns;
|
||||
|
||||
public class PatternMatching {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Object o = args[0];
|
||||
if (o instanceof String s) {
|
||||
System.out.printf("Object is a string %s", s);
|
||||
} else if(o instanceof Number n) {
|
||||
System.out.printf("Object is a number %n", n);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.switchpatterns;
|
||||
|
||||
public class SwitchStatement {
|
||||
|
||||
public static void main(String[] args) {
|
||||
final String b = "B";
|
||||
switch (args[0]) {
|
||||
case "A" -> System.out.println("Parameter is A");
|
||||
case b -> System.out.println("Parameter is b");
|
||||
default -> System.out.println("Parameter is unknown");
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.switchpatterns;
|
||||
|
||||
public class TypePatterns {
|
||||
|
||||
static double getDoubleUsingIf(Object o) {
|
||||
double result;
|
||||
|
||||
if (o instanceof Integer) {
|
||||
result = ((Integer) o).doubleValue();
|
||||
} else if (o instanceof Float) {
|
||||
result = ((Float) o).doubleValue();
|
||||
} else if (o instanceof String) {
|
||||
result = Double.parseDouble(((String) o));
|
||||
} else {
|
||||
result = 0d;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
static double getDoubleUsingSwitch(Object o) {
|
||||
return switch (o) {
|
||||
case Integer i -> i.doubleValue();
|
||||
case Float f -> f.doubleValue();
|
||||
case String s -> Double.parseDouble(s);
|
||||
default -> 0d;
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.switchpatterns;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static com.baeldung.switchpatterns.GuardedPatterns.*;
|
||||
|
||||
class GuardedPatternsUnitTest {
|
||||
|
||||
@Test
|
||||
void givenIfImplementation_whenUsingEmptyString_thenDoubleIsReturned() {
|
||||
assertEquals(0d, getDoubleValueUsingIf(""));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenIfImplementation_whenUsingNonEmptyString_thenDoubleIsReturned() {
|
||||
assertEquals(10d, getDoubleValueUsingIf("10"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPatternsImplementation_whenUsingEmptyString_thenDoubleIsReturned() {
|
||||
assertEquals(0d, getDoubleValueUsingGuardedPatterns(""));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPatternsImplementation_whenUsingNonEmptyString_thenDoubleIsReturned() {
|
||||
assertEquals(10d, getDoubleValueUsingGuardedPatterns("10"));
|
||||
}
|
||||
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.switchpatterns;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static com.baeldung.switchpatterns.HandlingNullValues.*;
|
||||
|
||||
class HandlingNullValuesUnitTest {
|
||||
|
||||
@Test
|
||||
void givenNullCaseInSwitch_whenUsingStringAsArgument_thenDoubleIsReturned() {
|
||||
assertEquals(10d, getDoubleUsingSwitchNullCase("10"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenTotalTypeInSwitch_whenUsingNullArgument_thenDoubleIsReturned() {
|
||||
assertEquals(0d, getDoubleUsingSwitchNullCase(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenTotalTypeInSwitch_whenUsingStringAsArgument_thenDoubleIsReturned() {
|
||||
assertEquals(10d, getDoubleUsingSwitchTotalType("10"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenNullCaseInSwitch_whenUsingNullArgument_thenDoubleIsReturned() {
|
||||
assertEquals(0d, getDoubleUsingSwitchTotalType(null));
|
||||
}
|
||||
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package com.baeldung.switchpatterns;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static com.baeldung.switchpatterns.ParenthesizedPatterns.*;
|
||||
|
||||
class ParenthesizedPatternsUnitTest {
|
||||
|
||||
@Test
|
||||
void givenIfImplementation_whenUsingEmptyString_thenDoubleIsReturned() {
|
||||
assertEquals(0d, getDoubleValueUsingIf(""));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenIfImplementation_whenUsingNonEmptyString_thenDoubleIsReturned() {
|
||||
assertEquals(10d, getDoubleValueUsingIf("10"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenIfImplementation_whenStringContainsSpecialChar_thenDoubleIsReturned() {
|
||||
assertEquals(0d, getDoubleValueUsingIf("@10"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPatternsImplementation_whenUsingEmptyString_thenDoubleIsReturned() {
|
||||
assertEquals(0d, getDoubleValueUsingParenthesizedPatterns(""));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPatternsImplementation_whenUsingNonEmptyString_thenDoubleIsReturned() {
|
||||
assertEquals(10d, getDoubleValueUsingParenthesizedPatterns("10"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPatternsImplementation_whenStringContainsSpecialChar_thenDoubleIsReturned() {
|
||||
assertEquals(0d, getDoubleValueUsingParenthesizedPatterns("@10"));
|
||||
}
|
||||
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package com.baeldung.switchpatterns;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static com.baeldung.switchpatterns.TypePatterns.*;
|
||||
|
||||
class TypePatternsUnitTest {
|
||||
|
||||
@Test
|
||||
void givenIfImplementation_whenUsingIntegerAsArgument_thenDoubleIsReturned() {
|
||||
assertEquals(10d, getDoubleUsingIf(10));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenIfImplementation_whenUsingDoubleAsArgument_thenDoubleIsReturned() {
|
||||
assertEquals(10d, getDoubleUsingIf(10.0f));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenIfImplementation_whenUsingStringAsArgument_thenDoubleIsReturned() {
|
||||
assertEquals(10d, getDoubleUsingIf("10"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenIfImplementation_whenUsingCharAsArgument_thenDoubleIsReturned() {
|
||||
assertEquals(0d, getDoubleUsingIf('c'));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenSwitchImplementation_whenUsingIntegerAsArgument_thenDoubleIsReturned() {
|
||||
assertEquals(10d, getDoubleUsingSwitch(10));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenSwitchImplementation_whenUsingDoubleAsArgument_thenDoubleIsReturned() {
|
||||
assertEquals(10d, getDoubleUsingSwitch(10.0f));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenSwitchImplementation_whenUsingStringAsArgument_thenDoubleIsReturned() {
|
||||
assertEquals(10d, getDoubleUsingSwitch("10"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenSwitchImplementation_whenUsingCharAsArgument_thenDoubleIsReturned() {
|
||||
assertEquals(0d, getDoubleUsingSwitch('c'));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -7,12 +7,11 @@
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-8-2</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
@@ -7,12 +7,11 @@
|
||||
<version>${project.parent.version}</version>
|
||||
<name>core-java-8-datetime-2</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
@@ -7,12 +7,11 @@
|
||||
<version>${project.parent.version}</version>
|
||||
<name>core-java-8-datetime</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
@@ -4,7 +4,6 @@ This module contains articles about Java 8 core features
|
||||
|
||||
### Relevant Articles:
|
||||
- [New Features in Java 8](https://www.baeldung.com/java-8-new-features)
|
||||
- [Guide to Java 8 groupingBy Collector](https://www.baeldung.com/java-groupingby-collector)
|
||||
- [Strategy Design Pattern in Java 8](https://www.baeldung.com/java-strategy-pattern)
|
||||
- [Guide to Java 8 Comparator.comparing()](https://www.baeldung.com/java-8-comparator-comparing)
|
||||
- [Guide to the Java 8 forEach](https://www.baeldung.com/foreach-java)
|
||||
|
||||
@@ -7,12 +7,11 @@
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-8</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
-36
@@ -1,36 +0,0 @@
|
||||
package com.baeldung.java_8_features.groupingby;
|
||||
|
||||
public class BlogPost {
|
||||
private String title;
|
||||
private String author;
|
||||
private BlogPostType type;
|
||||
private int likes;
|
||||
|
||||
public BlogPost(String title, String author, BlogPostType type, int likes) {
|
||||
this.title = title;
|
||||
this.author = author;
|
||||
this.type = type;
|
||||
this.likes = likes;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public String getAuthor() {
|
||||
return author;
|
||||
}
|
||||
|
||||
public BlogPostType getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public int getLikes() {
|
||||
return likes;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "BlogPost{" + "title='" + title + '\'' + ", type=" + type + ", likes=" + likes + '}';
|
||||
}
|
||||
}
|
||||
-5
@@ -1,5 +0,0 @@
|
||||
package com.baeldung.java_8_features.groupingby;
|
||||
|
||||
public enum BlogPostType {
|
||||
NEWS, REVIEW, GUIDE
|
||||
}
|
||||
-41
@@ -1,41 +0,0 @@
|
||||
package com.baeldung.java_8_features.groupingby;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public class Tuple {
|
||||
private final BlogPostType type;
|
||||
private final String author;
|
||||
|
||||
public Tuple(BlogPostType type, String author) {
|
||||
this.type = type;
|
||||
this.author = author;
|
||||
}
|
||||
|
||||
public BlogPostType getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public String getAuthor() {
|
||||
return author;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o)
|
||||
return true;
|
||||
if (o == null || getClass() != o.getClass())
|
||||
return false;
|
||||
Tuple tuple = (Tuple) o;
|
||||
return type == tuple.type && author.equals(tuple.author);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(type, author);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Tuple{" + "type=" + type + ", author='" + author + '\'' + '}';
|
||||
}
|
||||
}
|
||||
-215
@@ -1,215 +0,0 @@
|
||||
package com.baeldung.java_8_features.groupingby;
|
||||
|
||||
import static java.util.Comparator.comparingInt;
|
||||
import static java.util.stream.Collectors.averagingInt;
|
||||
import static java.util.stream.Collectors.counting;
|
||||
import static java.util.stream.Collectors.groupingBy;
|
||||
import static java.util.stream.Collectors.groupingByConcurrent;
|
||||
import static java.util.stream.Collectors.joining;
|
||||
import static java.util.stream.Collectors.mapping;
|
||||
import static java.util.stream.Collectors.maxBy;
|
||||
import static java.util.stream.Collectors.summarizingInt;
|
||||
import static java.util.stream.Collectors.summingInt;
|
||||
import static java.util.stream.Collectors.toList;
|
||||
import static java.util.stream.Collectors.toSet;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.EnumMap;
|
||||
import java.util.IntSummaryStatistics;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class Java8GroupingByCollectorUnitTest {
|
||||
|
||||
private static final List<BlogPost> posts = Arrays.asList(new BlogPost("News item 1", "Author 1", BlogPostType.NEWS, 15), new BlogPost("Tech review 1", "Author 2", BlogPostType.REVIEW, 5),
|
||||
new BlogPost("Programming guide", "Author 1", BlogPostType.GUIDE, 20), new BlogPost("News item 2", "Author 2", BlogPostType.NEWS, 35), new BlogPost("Tech review 2", "Author 1", BlogPostType.REVIEW, 15));
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByType_thenGetAMapBetweenTypeAndPosts() {
|
||||
Map<BlogPostType, List<BlogPost>> postsPerType = posts.stream()
|
||||
.collect(groupingBy(BlogPost::getType));
|
||||
|
||||
assertEquals(2, postsPerType.get(BlogPostType.NEWS)
|
||||
.size());
|
||||
assertEquals(1, postsPerType.get(BlogPostType.GUIDE)
|
||||
.size());
|
||||
assertEquals(2, postsPerType.get(BlogPostType.REVIEW)
|
||||
.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeAndTheirTitlesAreJoinedInAString_thenGetAMapBetweenTypeAndCsvTitles() {
|
||||
Map<BlogPostType, String> postsPerType = posts.stream()
|
||||
.collect(groupingBy(BlogPost::getType, mapping(BlogPost::getTitle, joining(", ", "Post titles: [", "]"))));
|
||||
|
||||
assertEquals("Post titles: [News item 1, News item 2]", postsPerType.get(BlogPostType.NEWS));
|
||||
assertEquals("Post titles: [Programming guide]", postsPerType.get(BlogPostType.GUIDE));
|
||||
assertEquals("Post titles: [Tech review 1, Tech review 2]", postsPerType.get(BlogPostType.REVIEW));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeAndSumTheLikes_thenGetAMapBetweenTypeAndPostLikes() {
|
||||
Map<BlogPostType, Integer> likesPerType = posts.stream()
|
||||
.collect(groupingBy(BlogPost::getType, summingInt(BlogPost::getLikes)));
|
||||
|
||||
assertEquals(50, likesPerType.get(BlogPostType.NEWS)
|
||||
.intValue());
|
||||
assertEquals(20, likesPerType.get(BlogPostType.REVIEW)
|
||||
.intValue());
|
||||
assertEquals(20, likesPerType.get(BlogPostType.GUIDE)
|
||||
.intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeInAnEnumMap_thenGetAnEnumMapBetweenTypeAndPosts() {
|
||||
EnumMap<BlogPostType, List<BlogPost>> postsPerType = posts.stream()
|
||||
.collect(groupingBy(BlogPost::getType, () -> new EnumMap<>(BlogPostType.class), toList()));
|
||||
|
||||
assertEquals(2, postsPerType.get(BlogPostType.NEWS)
|
||||
.size());
|
||||
assertEquals(1, postsPerType.get(BlogPostType.GUIDE)
|
||||
.size());
|
||||
assertEquals(2, postsPerType.get(BlogPostType.REVIEW)
|
||||
.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeInSets_thenGetAMapBetweenTypesAndSetsOfPosts() {
|
||||
Map<BlogPostType, Set<BlogPost>> postsPerType = posts.stream()
|
||||
.collect(groupingBy(BlogPost::getType, toSet()));
|
||||
|
||||
assertEquals(2, postsPerType.get(BlogPostType.NEWS)
|
||||
.size());
|
||||
assertEquals(1, postsPerType.get(BlogPostType.GUIDE)
|
||||
.size());
|
||||
assertEquals(2, postsPerType.get(BlogPostType.REVIEW)
|
||||
.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeConcurrently_thenGetAMapBetweenTypeAndPosts() {
|
||||
ConcurrentMap<BlogPostType, List<BlogPost>> postsPerType = posts.parallelStream()
|
||||
.collect(groupingByConcurrent(BlogPost::getType));
|
||||
|
||||
assertEquals(2, postsPerType.get(BlogPostType.NEWS)
|
||||
.size());
|
||||
assertEquals(1, postsPerType.get(BlogPostType.GUIDE)
|
||||
.size());
|
||||
assertEquals(2, postsPerType.get(BlogPostType.REVIEW)
|
||||
.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeAndAveragingLikes_thenGetAMapBetweenTypeAndAverageNumberOfLikes() {
|
||||
Map<BlogPostType, Double> averageLikesPerType = posts.stream()
|
||||
.collect(groupingBy(BlogPost::getType, averagingInt(BlogPost::getLikes)));
|
||||
|
||||
assertEquals(25, averageLikesPerType.get(BlogPostType.NEWS)
|
||||
.intValue());
|
||||
assertEquals(20, averageLikesPerType.get(BlogPostType.GUIDE)
|
||||
.intValue());
|
||||
assertEquals(10, averageLikesPerType.get(BlogPostType.REVIEW)
|
||||
.intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeAndCounted_thenGetAMapBetweenTypeAndNumberOfPosts() {
|
||||
Map<BlogPostType, Long> numberOfPostsPerType = posts.stream()
|
||||
.collect(groupingBy(BlogPost::getType, counting()));
|
||||
|
||||
assertEquals(2, numberOfPostsPerType.get(BlogPostType.NEWS)
|
||||
.intValue());
|
||||
assertEquals(1, numberOfPostsPerType.get(BlogPostType.GUIDE)
|
||||
.intValue());
|
||||
assertEquals(2, numberOfPostsPerType.get(BlogPostType.REVIEW)
|
||||
.intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeAndMaxingLikes_thenGetAMapBetweenTypeAndMaximumNumberOfLikes() {
|
||||
Map<BlogPostType, Optional<BlogPost>> maxLikesPerPostType = posts.stream()
|
||||
.collect(groupingBy(BlogPost::getType, maxBy(comparingInt(BlogPost::getLikes))));
|
||||
|
||||
assertTrue(maxLikesPerPostType.get(BlogPostType.NEWS)
|
||||
.isPresent());
|
||||
assertEquals(35, maxLikesPerPostType.get(BlogPostType.NEWS)
|
||||
.get()
|
||||
.getLikes());
|
||||
|
||||
assertTrue(maxLikesPerPostType.get(BlogPostType.GUIDE)
|
||||
.isPresent());
|
||||
assertEquals(20, maxLikesPerPostType.get(BlogPostType.GUIDE)
|
||||
.get()
|
||||
.getLikes());
|
||||
|
||||
assertTrue(maxLikesPerPostType.get(BlogPostType.REVIEW)
|
||||
.isPresent());
|
||||
assertEquals(15, maxLikesPerPostType.get(BlogPostType.REVIEW)
|
||||
.get()
|
||||
.getLikes());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByAuthorAndThenByType_thenGetAMapBetweenAuthorAndMapsBetweenTypeAndBlogPosts() {
|
||||
Map<String, Map<BlogPostType, List<BlogPost>>> map = posts.stream()
|
||||
.collect(groupingBy(BlogPost::getAuthor, groupingBy(BlogPost::getType)));
|
||||
|
||||
assertEquals(1, map.get("Author 1")
|
||||
.get(BlogPostType.NEWS)
|
||||
.size());
|
||||
assertEquals(1, map.get("Author 1")
|
||||
.get(BlogPostType.GUIDE)
|
||||
.size());
|
||||
assertEquals(1, map.get("Author 1")
|
||||
.get(BlogPostType.REVIEW)
|
||||
.size());
|
||||
|
||||
assertEquals(1, map.get("Author 2")
|
||||
.get(BlogPostType.NEWS)
|
||||
.size());
|
||||
assertEquals(1, map.get("Author 2")
|
||||
.get(BlogPostType.REVIEW)
|
||||
.size());
|
||||
assertNull(map.get("Author 2")
|
||||
.get(BlogPostType.GUIDE));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeAndSummarizingLikes_thenGetAMapBetweenTypeAndSummary() {
|
||||
Map<BlogPostType, IntSummaryStatistics> likeStatisticsPerType = posts.stream()
|
||||
.collect(groupingBy(BlogPost::getType, summarizingInt(BlogPost::getLikes)));
|
||||
|
||||
IntSummaryStatistics newsLikeStatistics = likeStatisticsPerType.get(BlogPostType.NEWS);
|
||||
|
||||
assertEquals(2, newsLikeStatistics.getCount());
|
||||
assertEquals(50, newsLikeStatistics.getSum());
|
||||
assertEquals(25.0, newsLikeStatistics.getAverage(), 0.001);
|
||||
assertEquals(35, newsLikeStatistics.getMax());
|
||||
assertEquals(15, newsLikeStatistics.getMin());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByComplexMapKeyType_thenGetAMapBetweenTupleAndList() {
|
||||
Map<Tuple, List<BlogPost>> postsPerTypeAndAuthor = posts.stream()
|
||||
.collect(groupingBy(post -> new Tuple(post.getType(), post.getAuthor())));
|
||||
|
||||
List<BlogPost> result = postsPerTypeAndAuthor.get(new Tuple(BlogPostType.GUIDE, "Author 1"));
|
||||
|
||||
assertThat(result.size()).isEqualTo(1);
|
||||
|
||||
BlogPost blogPost = result.get(0);
|
||||
|
||||
assertThat(blogPost.getTitle()).isEqualTo("Programming guide");
|
||||
assertThat(blogPost.getType()).isEqualTo(BlogPostType.GUIDE);
|
||||
assertThat(blogPost.getAuthor()).isEqualTo("Author 1");
|
||||
}
|
||||
}
|
||||
@@ -40,7 +40,7 @@
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-runner</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<version>${junit-platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
@@ -70,7 +70,6 @@
|
||||
<properties>
|
||||
<!-- testing -->
|
||||
<assertj.version>3.10.0</assertj.version>
|
||||
<junit.platform.version>1.2.0</junit.platform.version>
|
||||
<awaitility.version>1.7.0</awaitility.version>
|
||||
<maven.compiler.source>1.9</maven.compiler.source>
|
||||
<maven.compiler.target>1.9</maven.compiler.target>
|
||||
|
||||
@@ -6,7 +6,6 @@ This module contains articles about core Java features that have been introduced
|
||||
|
||||
- [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)
|
||||
- [Ahead of Time Compilation (AoT)](https://www.baeldung.com/ahead-of-time-compilation)
|
||||
- [Introduction to Java 9 StackWalking API](https://www.baeldung.com/java-9-stackwalking-api)
|
||||
|
||||
@@ -29,7 +29,7 @@
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-runner</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<version>${junit-platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@@ -39,7 +39,7 @@
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>incubator-features</id>
|
||||
@@ -131,7 +131,7 @@
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
|
||||
<build>
|
||||
<finalName>core-java-9-new-features</finalName>
|
||||
<plugins>
|
||||
@@ -158,7 +158,6 @@
|
||||
<rxjava.version>3.0.0</rxjava.version>
|
||||
<!-- testing -->
|
||||
<assertj.version>3.10.0</assertj.version>
|
||||
<junit.platform.version>1.2.0</junit.platform.version>
|
||||
<awaitility.version>4.0.2</awaitility.version>
|
||||
<maven.compiler.source>1.9</maven.compiler.source>
|
||||
<maven.compiler.target>1.9</maven.compiler.target>
|
||||
|
||||
-84
@@ -1,84 +0,0 @@
|
||||
/*
|
||||
* To change this license header, choose License Headers in Project Properties.
|
||||
* To change this template file, choose Tools | Templates
|
||||
* and open the template in the editor.
|
||||
*/
|
||||
package com.baeldung.httpclient;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.stream.Collectors;
|
||||
import jdk.incubator.http.HttpClient;
|
||||
import jdk.incubator.http.HttpRequest;
|
||||
import jdk.incubator.http.HttpRequest.BodyProcessor;
|
||||
import jdk.incubator.http.HttpResponse;
|
||||
import jdk.incubator.http.HttpResponse.BodyHandler;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author pkaria
|
||||
*/
|
||||
public class HttpClientExample {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
httpGetRequest();
|
||||
httpPostRequest();
|
||||
asynchronousRequest();
|
||||
asynchronousMultipleRequests();
|
||||
}
|
||||
|
||||
public static void httpGetRequest() throws URISyntaxException, IOException, InterruptedException {
|
||||
HttpClient client = HttpClient.newHttpClient();
|
||||
URI httpURI = new URI("http://jsonplaceholder.typicode.com/posts/1");
|
||||
HttpRequest request = HttpRequest.newBuilder(httpURI).GET()
|
||||
.headers("Accept-Enconding", "gzip, deflate").build();
|
||||
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandler.asString());
|
||||
String responseBody = response.body();
|
||||
int responseStatusCode = response.statusCode();
|
||||
System.out.println(responseBody);
|
||||
}
|
||||
|
||||
public static void httpPostRequest() throws URISyntaxException, IOException, InterruptedException {
|
||||
HttpClient client = HttpClient
|
||||
.newBuilder()
|
||||
.build();
|
||||
HttpRequest request = HttpRequest
|
||||
.newBuilder(new URI("http://jsonplaceholder.typicode.com/posts"))
|
||||
.POST(BodyProcessor.fromString("Sample Post Request"))
|
||||
.build();
|
||||
HttpResponse<String> response
|
||||
= client.send(request, HttpResponse.BodyHandler.asString());
|
||||
String responseBody = response.body();
|
||||
System.out.println(responseBody);
|
||||
}
|
||||
|
||||
public static void asynchronousRequest() throws URISyntaxException {
|
||||
HttpClient client = HttpClient.newHttpClient();
|
||||
URI httpURI = new URI("http://jsonplaceholder.typicode.com/posts/1");
|
||||
HttpRequest request = HttpRequest.newBuilder(httpURI).GET().build();
|
||||
CompletableFuture<HttpResponse<String>> futureResponse = client.sendAsync(request,
|
||||
HttpResponse.BodyHandler.asString());
|
||||
}
|
||||
|
||||
public static void asynchronousMultipleRequests() throws URISyntaxException {
|
||||
List<URI> targets = Arrays.asList(new URI("http://jsonplaceholder.typicode.com/posts/1"), new URI("http://jsonplaceholder.typicode.com/posts/2"));
|
||||
HttpClient client = HttpClient.newHttpClient();
|
||||
List<CompletableFuture<File>> futures = targets
|
||||
.stream()
|
||||
.map(target -> client
|
||||
.sendAsync(
|
||||
HttpRequest.newBuilder(target)
|
||||
.GET()
|
||||
.build(),
|
||||
BodyHandler.asFile(Paths.get("base", target.getPath())))
|
||||
.thenApply(response -> response.body())
|
||||
.thenApply(path -> path.toFile()))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
}
|
||||
-3
@@ -1,3 +0,0 @@
|
||||
module com.baeldung.httpclient {
|
||||
requires jdk.incubator.httpclient;
|
||||
}
|
||||
-218
@@ -1,218 +0,0 @@
|
||||
package com.baeldung.java9.httpclient;
|
||||
|
||||
import jdk.incubator.http.HttpClient;
|
||||
import jdk.incubator.http.HttpRequest;
|
||||
import jdk.incubator.http.HttpResponse;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.*;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.containsString;
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.hamcrest.collection.IsEmptyCollection.empty;
|
||||
import static org.hamcrest.core.IsNot.not;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
/**
|
||||
* Created by adam.
|
||||
*/
|
||||
public class HttpClientIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void shouldReturnSampleDataContentWhenConnectViaSystemProxy() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/post"))
|
||||
.headers("Content-Type", "text/plain;charset=UTF-8")
|
||||
.POST(HttpRequest.BodyProcessor.fromString("Sample body"))
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = HttpClient.newBuilder()
|
||||
.proxy(ProxySelector.getDefault())
|
||||
.build()
|
||||
.send(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
assertThat(response.body(), containsString("Sample body"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldNotFollowRedirectWhenSetToDefaultNever() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("http://stackoverflow.com"))
|
||||
.version(HttpClient.Version.HTTP_1_1)
|
||||
.GET()
|
||||
.build();
|
||||
HttpResponse<String> response = HttpClient.newBuilder()
|
||||
.build()
|
||||
.send(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_MOVED_PERM));
|
||||
assertThat(response.body(), containsString(""));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldFollowRedirectWhenSetToAlways() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("http://stackoverflow.com"))
|
||||
.version(HttpClient.Version.HTTP_1_1)
|
||||
.GET()
|
||||
.build();
|
||||
HttpResponse<String> response = HttpClient.newBuilder()
|
||||
.followRedirects(HttpClient.Redirect.ALWAYS)
|
||||
.build()
|
||||
.send(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
assertThat(response.finalRequest()
|
||||
.uri()
|
||||
.toString(), equalTo("https://stackoverflow.com/"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturnOKStatusForAuthenticatedAccess() throws URISyntaxException, IOException, InterruptedException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/basic-auth"))
|
||||
.GET()
|
||||
.build();
|
||||
HttpResponse<String> response = HttpClient.newBuilder()
|
||||
.authenticator(new Authenticator() {
|
||||
@Override
|
||||
protected PasswordAuthentication getPasswordAuthentication() {
|
||||
return new PasswordAuthentication("postman", "password".toCharArray());
|
||||
}
|
||||
})
|
||||
.build()
|
||||
.send(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldSendRequestAsync() throws URISyntaxException, InterruptedException, ExecutionException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/post"))
|
||||
.headers("Content-Type", "text/plain;charset=UTF-8")
|
||||
.POST(HttpRequest.BodyProcessor.fromString("Sample body"))
|
||||
.build();
|
||||
CompletableFuture<HttpResponse<String>> response = HttpClient.newBuilder()
|
||||
.build()
|
||||
.sendAsync(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
assertThat(response.get()
|
||||
.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldUseJustTwoThreadWhenProcessingSendAsyncRequest() throws URISyntaxException, InterruptedException, ExecutionException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/get"))
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
ExecutorService executorService = Executors.newFixedThreadPool(2);
|
||||
|
||||
CompletableFuture<HttpResponse<String>> response1 = HttpClient.newBuilder()
|
||||
.executor(executorService)
|
||||
.build()
|
||||
.sendAsync(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
CompletableFuture<HttpResponse<String>> response2 = HttpClient.newBuilder()
|
||||
.executor(executorService)
|
||||
.build()
|
||||
.sendAsync(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
CompletableFuture<HttpResponse<String>> response3 = HttpClient.newBuilder()
|
||||
.executor(executorService)
|
||||
.build()
|
||||
.sendAsync(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
CompletableFuture.allOf(response1, response2, response3)
|
||||
.join();
|
||||
|
||||
assertThat(response1.get()
|
||||
.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
assertThat(response2.get()
|
||||
.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
assertThat(response3.get()
|
||||
.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldNotStoreCookieWhenPolicyAcceptNone() throws URISyntaxException, IOException, InterruptedException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/get"))
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
HttpClient httpClient = HttpClient.newBuilder()
|
||||
.cookieManager(new CookieManager(null, CookiePolicy.ACCEPT_NONE))
|
||||
.build();
|
||||
|
||||
httpClient.send(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
assertThat(httpClient.cookieManager()
|
||||
.get()
|
||||
.getCookieStore()
|
||||
.getCookies(), empty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldStoreCookieWhenPolicyAcceptAll() throws URISyntaxException, IOException, InterruptedException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/get"))
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
HttpClient httpClient = HttpClient.newBuilder()
|
||||
.cookieManager(new CookieManager(null, CookiePolicy.ACCEPT_ALL))
|
||||
.build();
|
||||
|
||||
httpClient.send(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
assertThat(httpClient.cookieManager()
|
||||
.get()
|
||||
.getCookieStore()
|
||||
.getCookies(), not(empty()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldProcessMultipleRequestViaStream() throws URISyntaxException, ExecutionException, InterruptedException {
|
||||
List<URI> targets = Arrays.asList(new URI("https://postman-echo.com/get?foo1=bar1"), new URI("https://postman-echo.com/get?foo2=bar2"));
|
||||
|
||||
HttpClient client = HttpClient.newHttpClient();
|
||||
|
||||
List<CompletableFuture<String>> futures = targets.stream()
|
||||
.map(target -> client.sendAsync(HttpRequest.newBuilder(target)
|
||||
.GET()
|
||||
.build(), HttpResponse.BodyHandler.asString())
|
||||
.thenApply(response -> response.body()))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
|
||||
.join();
|
||||
|
||||
if (futures.get(0)
|
||||
.get()
|
||||
.contains("foo1")) {
|
||||
assertThat(futures.get(0)
|
||||
.get(), containsString("bar1"));
|
||||
assertThat(futures.get(1)
|
||||
.get(), containsString("bar2"));
|
||||
} else {
|
||||
assertThat(futures.get(1)
|
||||
.get(), containsString("bar2"));
|
||||
assertThat(futures.get(1)
|
||||
.get(), containsString("bar1"));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
-171
@@ -1,171 +0,0 @@
|
||||
package com.baeldung.java9.httpclient;
|
||||
|
||||
import jdk.incubator.http.HttpClient;
|
||||
import jdk.incubator.http.HttpRequest;
|
||||
import jdk.incubator.http.HttpResponse;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.nio.file.Paths;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Duration;
|
||||
|
||||
import static java.time.temporal.ChronoUnit.SECONDS;
|
||||
import static org.hamcrest.CoreMatchers.containsString;
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
/**
|
||||
* Created by adam.
|
||||
*/
|
||||
public class HttpRequestIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void shouldReturnStatusOKWhenSendGetRequest() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/get"))
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = HttpClient.newHttpClient()
|
||||
.send(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldUseHttp2WhenWebsiteUsesHttp2() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://stackoverflow.com"))
|
||||
.version(HttpClient.Version.HTTP_2)
|
||||
.GET()
|
||||
.build();
|
||||
HttpResponse<String> response = HttpClient.newHttpClient()
|
||||
.send(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
assertThat(response.version(), equalTo(HttpClient.Version.HTTP_2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldFallbackToHttp1_1WhenWebsiteDoesNotUseHttp2() throws IOException, InterruptedException, URISyntaxException, NoSuchAlgorithmException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/get"))
|
||||
.version(HttpClient.Version.HTTP_2)
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = HttpClient.newHttpClient()
|
||||
.send(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
assertThat(response.version(), equalTo(HttpClient.Version.HTTP_1_1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturnStatusOKWhenSendGetRequestWithDummyHeaders() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/get"))
|
||||
.headers("key1", "value1", "key2", "value2")
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = HttpClient.newHttpClient()
|
||||
.send(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturnStatusOKWhenSendGetRequestTimeoutSet() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/get"))
|
||||
.timeout(Duration.of(10, SECONDS))
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = HttpClient.newHttpClient()
|
||||
.send(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturnNoContentWhenPostWithNoBody() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/post"))
|
||||
.POST(HttpRequest.noBody())
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = HttpClient.newHttpClient()
|
||||
.send(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturnSampleDataContentWhenPostWithBodyText() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/post"))
|
||||
.headers("Content-Type", "text/plain;charset=UTF-8")
|
||||
.POST(HttpRequest.BodyProcessor.fromString("Sample request body"))
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = HttpClient.newHttpClient()
|
||||
.send(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
assertThat(response.body(), containsString("Sample request body"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturnSampleDataContentWhenPostWithInputStream() throws IOException, InterruptedException, URISyntaxException {
|
||||
byte[] sampleData = "Sample request body".getBytes();
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/post"))
|
||||
.headers("Content-Type", "text/plain;charset=UTF-8")
|
||||
.POST(HttpRequest.BodyProcessor.fromInputStream(() -> new ByteArrayInputStream(sampleData)))
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = HttpClient.newHttpClient()
|
||||
.send(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
assertThat(response.body(), containsString("Sample request body"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturnSampleDataContentWhenPostWithByteArrayProcessorStream() throws IOException, InterruptedException, URISyntaxException {
|
||||
byte[] sampleData = "Sample request body".getBytes();
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/post"))
|
||||
.headers("Content-Type", "text/plain;charset=UTF-8")
|
||||
.POST(HttpRequest.BodyProcessor.fromByteArray(sampleData))
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = HttpClient.newHttpClient()
|
||||
.send(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
assertThat(response.body(), containsString("Sample request body"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturnSampleDataContentWhenPostWithFileProcessorStream() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/post"))
|
||||
.headers("Content-Type", "text/plain;charset=UTF-8")
|
||||
.POST(HttpRequest.BodyProcessor.fromFile(Paths.get("src/test/resources/sample.txt")))
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = HttpClient.newHttpClient()
|
||||
.send(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
assertThat(response.body(), containsString("Sample file content"));
|
||||
}
|
||||
|
||||
}
|
||||
-55
@@ -1,55 +0,0 @@
|
||||
package com.baeldung.java9.httpclient;
|
||||
|
||||
import jdk.incubator.http.HttpClient;
|
||||
import jdk.incubator.http.HttpRequest;
|
||||
import jdk.incubator.http.HttpResponse;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.hamcrest.Matchers.isEmptyString;
|
||||
import static org.hamcrest.core.IsNot.not;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
/**
|
||||
* Created by adam.
|
||||
*/
|
||||
public class HttpResponseIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void shouldReturnStatusOKWhenSendGetRequest() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("https://postman-echo.com/get"))
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = HttpClient.newHttpClient()
|
||||
.send(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
|
||||
assertThat(response.body(), not(isEmptyString()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldResponseURIDifferentThanRequestUIRWhenRedirect() throws IOException, InterruptedException, URISyntaxException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(new URI("http://stackoverflow.com"))
|
||||
.version(HttpClient.Version.HTTP_1_1)
|
||||
.GET()
|
||||
.build();
|
||||
HttpResponse<String> response = HttpClient.newBuilder()
|
||||
.followRedirects(HttpClient.Redirect.ALWAYS)
|
||||
.build()
|
||||
.send(request, HttpResponse.BodyHandler.asString());
|
||||
|
||||
assertThat(request.uri()
|
||||
.toString(), equalTo("http://stackoverflow.com"));
|
||||
assertThat(response.uri()
|
||||
.toString(), equalTo("https://stackoverflow.com/"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -35,7 +35,7 @@
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-runner</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<version>${junit-platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@@ -80,7 +80,6 @@
|
||||
<properties>
|
||||
<!-- testing -->
|
||||
<assertj.version>3.10.0</assertj.version>
|
||||
<junit.platform.version>1.2.0</junit.platform.version>
|
||||
<awaitility.version>1.7.0</awaitility.version>
|
||||
<maven.compiler.source>1.9</maven.compiler.source>
|
||||
<maven.compiler.target>1.9</maven.compiler.target>
|
||||
|
||||
@@ -12,3 +12,4 @@
|
||||
- [Efficient Word Frequency Calculator in Java](https://www.baeldung.com/java-word-frequency)
|
||||
- [Why Missing Annotations Don’t Cause ClassNotFoundException](https://www.baeldung.com/classnotfoundexception-missing-annotation)
|
||||
- [Valid @SuppressWarnings Warning Names](https://www.baeldung.com/java-suppresswarnings-valid-names)
|
||||
- [Get a Field’s Annotations Using Reflection](https://www.baeldung.com/java-get-field-annotations)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
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-annotations</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
@@ -12,9 +12,21 @@
|
||||
<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.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj-core.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<assertj-core.version>3.10.0</assertj-core.version>
|
||||
</properties>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-annotations</finalName>
|
||||
<resources>
|
||||
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.readannotations;
|
||||
|
||||
public class ClassWithAnnotations {
|
||||
|
||||
@FirstAnnotation
|
||||
@SecondAnnotation
|
||||
@ThirdAnnotation
|
||||
private String classMember;
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.readannotations;
|
||||
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface FirstAnnotation {
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.readannotations;
|
||||
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface SecondAnnotation {
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.readannotations;
|
||||
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
|
||||
@Retention(RetentionPolicy.SOURCE)
|
||||
public @interface ThirdAnnotation {
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.readannotations;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.lang.reflect.Field;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class ClassWithAnnotationsUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenCallingGetDeclaredAnnotations_thenOnlyRuntimeAnnotationsAreAvailable() throws NoSuchFieldException {
|
||||
Field classMemberField = ClassWithAnnotations.class.getDeclaredField("classMember");
|
||||
Annotation[] annotations = classMemberField.getDeclaredAnnotations();
|
||||
assertThat(annotations).hasSize(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCallingIsAnnotationPresent_thenOnlyRuntimeAnnotationsAreAvailable() throws NoSuchFieldException {
|
||||
Field classMemberField = ClassWithAnnotations.class.getDeclaredField("classMember");
|
||||
assertThat(classMemberField.isAnnotationPresent(FirstAnnotation.class)).isTrue();
|
||||
assertThat(classMemberField.isAnnotationPresent(SecondAnnotation.class)).isTrue();
|
||||
assertThat(classMemberField.isAnnotationPresent(ThirdAnnotation.class)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCallingGetDeclaredAnnotationsOrGetAnnotations_thenSameAnnotationsAreReturned() throws NoSuchFieldException {
|
||||
Field classMemberField = ClassWithAnnotations.class.getDeclaredField("classMember");
|
||||
Annotation[] declaredAnnotations = classMemberField.getDeclaredAnnotations();
|
||||
Annotation[] annotations = classMemberField.getAnnotations();
|
||||
assertThat(declaredAnnotations).containsExactly(annotations);
|
||||
}
|
||||
}
|
||||
@@ -5,3 +5,4 @@ This module contains articles about arrays conversion in Java
|
||||
## Relevant Articles
|
||||
- [Convert a Float to a Byte Array in Java](https://www.baeldung.com/java-convert-float-to-byte-array)
|
||||
- [Converting Between Stream and Array in Java](https://www.baeldung.com/java-stream-to-array)
|
||||
- [Convert a Byte Array to a Numeric Representation in Java](https://www.baeldung.com/java-byte-array-to-number)
|
||||
|
||||
@@ -19,6 +19,11 @@
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
|
||||
+281
@@ -0,0 +1,281 @@
|
||||
package com.baeldung.array.conversions;
|
||||
|
||||
import com.google.common.primitives.Ints;
|
||||
import com.google.common.primitives.Longs;
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.apache.commons.lang3.Conversion;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.Arrays;
|
||||
|
||||
class ByteArrayToNumericRepresentation {
|
||||
|
||||
static int convertByteArrayToIntUsingShiftOperator(byte[] bytes) {
|
||||
int value = 0;
|
||||
for (byte b : bytes) {
|
||||
value = (value << 8) + (b & 0xFF);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
static byte[] convertIntToByteArrayUsingShiftOperator(int value) {
|
||||
byte[] bytes = new byte[Integer.BYTES];
|
||||
int length = bytes.length;
|
||||
for (int i = 0; i < length; i++) {
|
||||
bytes[length - i - 1] = (byte) (value & 0xFF);
|
||||
value >>= 8;
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
static long convertByteArrayToLongUsingShiftOperator(byte[] bytes) {
|
||||
long value = 0;
|
||||
for (byte b : bytes) {
|
||||
value <<= 8;
|
||||
value |= (b & 0xFF);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
static byte[] convertLongToByteArrayUsingShiftOperator(long value) {
|
||||
byte[] bytes = new byte[Long.BYTES];
|
||||
int length = bytes.length;
|
||||
for (int i = 0; i < length; i++) {
|
||||
bytes[length - i - 1] = (byte) (value & 0xFF);
|
||||
value >>= 8;
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
static float convertByteArrayToFloatUsingShiftOperator(byte[] bytes) {
|
||||
// convert bytes to int
|
||||
int intValue = 0;
|
||||
for (byte b : bytes) {
|
||||
intValue = (intValue << 8) + (b & 0xFF);
|
||||
}
|
||||
|
||||
// convert int to float
|
||||
return Float.intBitsToFloat(intValue);
|
||||
}
|
||||
|
||||
static byte[] convertFloatToByteArrayUsingShiftOperator(float value) {
|
||||
// convert float to int
|
||||
int intValue = Float.floatToIntBits(value);
|
||||
|
||||
// convert int to bytes
|
||||
byte[] bytes = new byte[Float.BYTES];
|
||||
int length = bytes.length;
|
||||
for (int i = 0; i < length; i++) {
|
||||
bytes[length - i - 1] = (byte) (intValue & 0xFF);
|
||||
intValue >>= 8;
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
static double convertingByteArrayToDoubleUsingShiftOperator(byte[] bytes) {
|
||||
long longValue = 0;
|
||||
for (byte b : bytes) {
|
||||
longValue = (longValue << 8) + (b & 0xFF);
|
||||
}
|
||||
|
||||
return Double.longBitsToDouble(longValue);
|
||||
}
|
||||
|
||||
static byte[] convertDoubleToByteArrayUsingShiftOperator(double value) {
|
||||
long longValue = Double.doubleToLongBits(value);
|
||||
|
||||
byte[] bytes = new byte[Double.BYTES];
|
||||
int length = bytes.length;
|
||||
for (int i = 0; i < length; i++) {
|
||||
bytes[length - i - 1] = (byte) (longValue & 0xFF);
|
||||
longValue >>= 8;
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
static int convertByteArrayToIntUsingByteBuffer(byte[] bytes) {
|
||||
ByteBuffer buffer = ByteBuffer.allocate(Integer.BYTES);
|
||||
buffer.put(bytes);
|
||||
buffer.rewind();
|
||||
return buffer.getInt();
|
||||
}
|
||||
|
||||
static byte[] convertIntToByteArrayUsingByteBuffer(int value) {
|
||||
ByteBuffer buffer = ByteBuffer.allocate(Integer.BYTES);
|
||||
buffer.putInt(value);
|
||||
buffer.rewind();
|
||||
return buffer.array();
|
||||
}
|
||||
|
||||
static long convertByteArrayToLongUsingByteBuffer(byte[] bytes) {
|
||||
ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
|
||||
buffer.put(bytes);
|
||||
buffer.rewind();
|
||||
return buffer.getLong();
|
||||
}
|
||||
|
||||
static byte[] convertLongToByteArrayUsingByteBuffer(long value) {
|
||||
ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
|
||||
buffer.putLong(value);
|
||||
buffer.rewind();
|
||||
return buffer.array();
|
||||
}
|
||||
|
||||
static float convertByteArrayToFloatUsingByteBuffer(byte[] bytes) {
|
||||
ByteBuffer buffer = ByteBuffer.allocate(Float.BYTES);
|
||||
buffer.put(bytes);
|
||||
buffer.rewind();
|
||||
return buffer.getFloat();
|
||||
}
|
||||
|
||||
static byte[] convertFloatToByteArrayUsingByteBuffer(float value) {
|
||||
ByteBuffer buffer = ByteBuffer.allocate(Float.BYTES);
|
||||
buffer.putFloat(value);
|
||||
buffer.rewind();
|
||||
return buffer.array();
|
||||
}
|
||||
|
||||
static double convertByteArrayToDoubleUsingByteBuffer(byte[] bytes) {
|
||||
ByteBuffer buffer = ByteBuffer.allocate(Double.BYTES);
|
||||
buffer.put(bytes);
|
||||
buffer.rewind();
|
||||
return buffer.getDouble();
|
||||
}
|
||||
|
||||
static byte[] convertDoubleToByteArrayUsingByteBuffer(double value) {
|
||||
ByteBuffer buffer = ByteBuffer.allocate(Double.BYTES);
|
||||
buffer.putDouble(value);
|
||||
buffer.rewind();
|
||||
return buffer.array();
|
||||
}
|
||||
|
||||
static int convertByteArrayToIntUsingBigInteger(byte[] bytes) {
|
||||
return new BigInteger(bytes).intValue();
|
||||
}
|
||||
|
||||
static byte[] convertIntToByteArrayUsingBigInteger(int value) {
|
||||
return BigInteger.valueOf(value).toByteArray();
|
||||
}
|
||||
|
||||
static long convertByteArrayToLongUsingBigInteger(byte[] bytes) {
|
||||
return new BigInteger(bytes).longValue();
|
||||
}
|
||||
|
||||
static byte[] convertLongToByteArrayUsingBigInteger(long value) {
|
||||
return BigInteger.valueOf(value).toByteArray();
|
||||
}
|
||||
|
||||
static float convertByteArrayToFloatUsingBigInteger(byte[] bytes) {
|
||||
int intValue = new BigInteger(bytes).intValue();
|
||||
return Float.intBitsToFloat(intValue);
|
||||
}
|
||||
|
||||
static byte[] convertFloatToByteArrayUsingBigInteger(float value) {
|
||||
int intValue = Float.floatToIntBits(value);
|
||||
return BigInteger.valueOf(intValue).toByteArray();
|
||||
}
|
||||
|
||||
static double convertByteArrayToDoubleUsingBigInteger(byte[] bytes) {
|
||||
long longValue = new BigInteger(bytes).longValue();
|
||||
return Double.longBitsToDouble(longValue);
|
||||
}
|
||||
|
||||
static byte[] convertDoubleToByteArrayUsingBigInteger(double value) {
|
||||
long longValue = Double.doubleToLongBits(value);
|
||||
return BigInteger.valueOf(longValue).toByteArray();
|
||||
}
|
||||
|
||||
static int convertingByteArrayToIntUsingGuava(byte[] bytes) {
|
||||
return Ints.fromByteArray(bytes);
|
||||
}
|
||||
|
||||
static byte[] convertIntToByteArrayUsingGuava(int value) {
|
||||
return Ints.toByteArray(value);
|
||||
}
|
||||
|
||||
static long convertByteArrayToLongUsingGuava(byte[] bytes) {
|
||||
return Longs.fromByteArray(bytes);
|
||||
}
|
||||
|
||||
static byte[] convertLongToByteArrayUsingGuava(long value) {
|
||||
return Longs.toByteArray(value);
|
||||
}
|
||||
|
||||
static float convertByteArrayToFloatUsingGuava(byte[] bytes) {
|
||||
int intValue = Ints.fromByteArray(bytes);
|
||||
return Float.intBitsToFloat(intValue);
|
||||
}
|
||||
|
||||
static byte[] convertFloatToByteArrayUsingGuava(float value) {
|
||||
int intValue = Float.floatToIntBits(value);
|
||||
return Ints.toByteArray(intValue);
|
||||
}
|
||||
|
||||
static double convertByteArrayToDoubleUsingGuava(byte[] bytes) {
|
||||
long longValue = Longs.fromByteArray(bytes);
|
||||
return Double.longBitsToDouble(longValue);
|
||||
}
|
||||
|
||||
static byte[] convertDoubleToByteArrayUsingGuava(double value) {
|
||||
long longValue = Double.doubleToLongBits(value);
|
||||
return Longs.toByteArray(longValue);
|
||||
}
|
||||
|
||||
static int convertByteArrayToIntUsingCommonsLang(byte[] bytes) {
|
||||
byte[] copyBytes = Arrays.copyOf(bytes, bytes.length);
|
||||
ArrayUtils.reverse(copyBytes);
|
||||
return Conversion.byteArrayToInt(copyBytes, 0, 0, 0, copyBytes.length);
|
||||
}
|
||||
|
||||
static byte[] convertIntToByteArrayUsingCommonsLang(int value) {
|
||||
byte[] bytes = new byte[Integer.BYTES];
|
||||
Conversion.intToByteArray(value, 0, bytes, 0, bytes.length);
|
||||
ArrayUtils.reverse(bytes);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
static long convertByteArrayToLongUsingCommonsLang(byte[] bytes) {
|
||||
byte[] copyBytes = Arrays.copyOf(bytes, bytes.length);
|
||||
ArrayUtils.reverse(copyBytes);
|
||||
return Conversion.byteArrayToLong(copyBytes, 0, 0, 0, copyBytes.length);
|
||||
}
|
||||
|
||||
static byte[] convertLongToByteArrayUsingCommonsLang(long value) {
|
||||
byte[] bytes = new byte[Long.BYTES];
|
||||
Conversion.longToByteArray(value, 0, bytes, 0, bytes.length);
|
||||
ArrayUtils.reverse(bytes);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
static float convertByteArrayToFloatUsingCommonsLang(byte[] bytes) {
|
||||
byte[] copyBytes = Arrays.copyOf(bytes, bytes.length);
|
||||
ArrayUtils.reverse(copyBytes);
|
||||
int intValue = Conversion.byteArrayToInt(copyBytes, 0, 0, 0, copyBytes.length);
|
||||
return Float.intBitsToFloat(intValue);
|
||||
}
|
||||
|
||||
static byte[] convertFloatToByteArrayUsingCommonsLang(float value) {
|
||||
int intValue = Float.floatToIntBits(value);
|
||||
byte[] bytes = new byte[Float.BYTES];
|
||||
Conversion.intToByteArray(intValue, 0, bytes, 0, bytes.length);
|
||||
ArrayUtils.reverse(bytes);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
static double convertByteArrayToDoubleUsingCommonsLang(byte[] bytes) {
|
||||
byte[] copyBytes = Arrays.copyOf(bytes, bytes.length);
|
||||
ArrayUtils.reverse(copyBytes);
|
||||
long longValue = Conversion.byteArrayToLong(copyBytes, 0, 0, 0, copyBytes.length);
|
||||
return Double.longBitsToDouble(longValue);
|
||||
}
|
||||
|
||||
static byte[] convertDoubleToByteArrayUsingCommonsLang(double value) {
|
||||
long longValue = Double.doubleToLongBits(value);
|
||||
byte[] bytes = new byte[Long.BYTES];
|
||||
Conversion.longToByteArray(longValue, 0, bytes, 0, bytes.length);
|
||||
ArrayUtils.reverse(bytes);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
}
|
||||
+316
@@ -0,0 +1,316 @@
|
||||
package com.baeldung.array.conversions;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static com.baeldung.array.conversions.ByteArrayToNumericRepresentation.*;
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class ByteArrayToNumericRepresentationUnitTest {
|
||||
private static final byte[] INT_BYTE_ARRAY = new byte[]{
|
||||
(byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE
|
||||
};
|
||||
private static final int INT_VALUE = 0xCAFEBABE;
|
||||
|
||||
|
||||
private static final byte[] FLOAT_BYTE_ARRAY = new byte[]{
|
||||
(byte) 0x40, (byte) 0x48, (byte) 0xF5, (byte) 0xC3
|
||||
};
|
||||
private static final float FLOAT_VALUE = 3.14F;
|
||||
|
||||
|
||||
private static final byte[] LONG_BYTE_ARRAY = new byte[]{
|
||||
(byte) 0x01, (byte) 0x23, (byte) 0x45, (byte) 0x67,
|
||||
(byte) 0x89, (byte) 0xAB, (byte) 0xCD, (byte) 0xEF
|
||||
};
|
||||
private static final long LONG_VALUE = 0x0123456789ABCDEFL;
|
||||
|
||||
|
||||
private static final byte[] DOUBLE_BYTE_ARRAY = new byte[]{
|
||||
(byte) 0x3F, (byte) 0xE3, (byte) 0xC6, (byte) 0xA7,
|
||||
(byte) 0xEF, (byte) 0x9D, (byte) 0xB2, (byte) 0x2D
|
||||
};
|
||||
private static final double DOUBLE_VALUE = 0.618D;
|
||||
|
||||
|
||||
@Test
|
||||
public void givenShiftOperator_whenConvertingByteArrayToInt_thenSuccess() {
|
||||
int value = convertByteArrayToIntUsingShiftOperator(INT_BYTE_ARRAY);
|
||||
|
||||
assertEquals(INT_VALUE, value);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenShiftOperator_whenConvertingIntToByteArray_thenSuccess() {
|
||||
byte[] bytes = convertIntToByteArrayUsingShiftOperator(INT_VALUE);
|
||||
|
||||
assertArrayEquals(INT_BYTE_ARRAY, bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenShiftOperator_whenConvertingByteArrayToLong_thenSuccess() {
|
||||
long value = convertByteArrayToLongUsingShiftOperator(LONG_BYTE_ARRAY);
|
||||
|
||||
assertEquals(LONG_VALUE, value);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenShiftOperator_whenConvertingLongToByteArray_thenSuccess() {
|
||||
byte[] bytes = convertLongToByteArrayUsingShiftOperator(LONG_VALUE);
|
||||
|
||||
assertArrayEquals(LONG_BYTE_ARRAY, bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenShiftOperator_whenConvertingByteArrayToFloat_thenSuccess() {
|
||||
float value = convertByteArrayToFloatUsingShiftOperator(FLOAT_BYTE_ARRAY);
|
||||
|
||||
assertEquals(Float.floatToIntBits(FLOAT_VALUE), Float.floatToIntBits(value));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenShiftOperator_whenConvertingFloatToByteArray_thenSuccess() {
|
||||
byte[] bytes = convertFloatToByteArrayUsingShiftOperator(FLOAT_VALUE);
|
||||
|
||||
assertArrayEquals(FLOAT_BYTE_ARRAY, bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenShiftOperator_whenConvertingByteArrayToDouble_thenSuccess() {
|
||||
double value = convertingByteArrayToDoubleUsingShiftOperator(DOUBLE_BYTE_ARRAY);
|
||||
|
||||
assertEquals(Double.doubleToLongBits(DOUBLE_VALUE), Double.doubleToLongBits(value));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenShiftOperator_whenConvertingDoubleToByteArray_thenSuccess() {
|
||||
byte[] bytes = convertDoubleToByteArrayUsingShiftOperator(DOUBLE_VALUE);
|
||||
|
||||
assertArrayEquals(DOUBLE_BYTE_ARRAY, bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenByteBuffer_whenConvertingByteArrayToInt_thenSuccess() {
|
||||
int value = convertByteArrayToIntUsingByteBuffer(INT_BYTE_ARRAY);
|
||||
|
||||
assertEquals(INT_VALUE, value);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenByteBuffer_whenConvertingIntToByteArray_thenSuccess() {
|
||||
byte[] bytes = convertIntToByteArrayUsingByteBuffer(INT_VALUE);
|
||||
|
||||
assertArrayEquals(INT_BYTE_ARRAY, bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenByteBuffer_whenConvertingByteArrayToLong_thenSuccess() {
|
||||
long value = convertByteArrayToLongUsingByteBuffer(LONG_BYTE_ARRAY);
|
||||
|
||||
assertEquals(LONG_VALUE, value);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenByteBuffer_whenConvertingLongToByteArray_thenSuccess() {
|
||||
byte[] bytes = convertLongToByteArrayUsingByteBuffer(LONG_VALUE);
|
||||
|
||||
assertArrayEquals(LONG_BYTE_ARRAY, bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenByteBuffer_whenConvertingByteArrayToFloat_thenSuccess() {
|
||||
float value = convertByteArrayToFloatUsingByteBuffer(FLOAT_BYTE_ARRAY);
|
||||
|
||||
assertEquals(Float.floatToIntBits(FLOAT_VALUE), Float.floatToIntBits(value));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenByteBuffer_whenConvertingFloatToByteArray_thenSuccess() {
|
||||
byte[] bytes = convertFloatToByteArrayUsingByteBuffer(FLOAT_VALUE);
|
||||
|
||||
assertArrayEquals(FLOAT_BYTE_ARRAY, bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenByteBuffer_whenConvertingByteArrayToDouble_thenSuccess() {
|
||||
double value = convertByteArrayToDoubleUsingByteBuffer(DOUBLE_BYTE_ARRAY);
|
||||
|
||||
assertEquals(Double.doubleToLongBits(DOUBLE_VALUE), Double.doubleToLongBits(value));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenByteBuffer_whenConvertingDoubleToByteArray_thenSuccess() {
|
||||
byte[] bytes = convertDoubleToByteArrayUsingByteBuffer(DOUBLE_VALUE);
|
||||
|
||||
assertArrayEquals(DOUBLE_BYTE_ARRAY, bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBigInteger_whenConvertingByteArrayToInt_thenSuccess() {
|
||||
int value = convertByteArrayToIntUsingBigInteger(INT_BYTE_ARRAY);
|
||||
|
||||
assertEquals(INT_VALUE, value);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBigInteger_whenConvertingIntToByteArray_thenSuccess() {
|
||||
byte[] bytes = convertIntToByteArrayUsingBigInteger(INT_VALUE);
|
||||
|
||||
assertArrayEquals(INT_BYTE_ARRAY, bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBigInteger_whenConvertingByteArrayToLong_thenSuccess() {
|
||||
long value = convertByteArrayToLongUsingBigInteger(LONG_BYTE_ARRAY);
|
||||
|
||||
assertEquals(LONG_VALUE, value);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBigInteger_whenConvertingLongToByteArray_thenSuccess() {
|
||||
byte[] bytes = convertLongToByteArrayUsingBigInteger(LONG_VALUE);
|
||||
|
||||
assertArrayEquals(LONG_BYTE_ARRAY, bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBigInteger_whenConvertingByteArrayToFloat_thenSuccess() {
|
||||
float value = convertByteArrayToFloatUsingBigInteger(FLOAT_BYTE_ARRAY);
|
||||
|
||||
assertEquals(Float.floatToIntBits(FLOAT_VALUE), Float.floatToIntBits(value));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBigInteger_whenConvertingFloatToByteArray_thenSuccess() {
|
||||
byte[] bytes = convertFloatToByteArrayUsingBigInteger(FLOAT_VALUE);
|
||||
|
||||
assertArrayEquals(FLOAT_BYTE_ARRAY, bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBigInteger_whenConvertingByteArrayToDouble_thenSuccess() {
|
||||
double value = convertByteArrayToDoubleUsingBigInteger(DOUBLE_BYTE_ARRAY);
|
||||
|
||||
assertEquals(Double.doubleToLongBits(DOUBLE_VALUE), Double.doubleToLongBits(value));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBigInteger_whenConvertingDoubleToByteArray_thenSuccess() {
|
||||
byte[] bytes = convertDoubleToByteArrayUsingBigInteger(DOUBLE_VALUE);
|
||||
|
||||
assertArrayEquals(DOUBLE_BYTE_ARRAY, bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGuava_whenConvertingByteArrayToInt_thenSuccess() {
|
||||
int value = convertingByteArrayToIntUsingGuava(INT_BYTE_ARRAY);
|
||||
|
||||
assertEquals(INT_VALUE, value);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGuava_whenConvertingIntToByteArray_thenSuccess() {
|
||||
byte[] bytes = convertIntToByteArrayUsingGuava(INT_VALUE);
|
||||
|
||||
assertArrayEquals(INT_BYTE_ARRAY, bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGuava_whenConvertingByteArrayToLong_thenSuccess() {
|
||||
long value = convertByteArrayToLongUsingGuava(LONG_BYTE_ARRAY);
|
||||
|
||||
assertEquals(LONG_VALUE, value);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGuava_whenConvertingLongToByteArray_thenSuccess() {
|
||||
byte[] bytes = convertLongToByteArrayUsingGuava(LONG_VALUE);
|
||||
|
||||
assertArrayEquals(LONG_BYTE_ARRAY, bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGuava_whenConvertingByteArrayToFloat_thenSuccess() {
|
||||
float value = convertByteArrayToFloatUsingGuava(FLOAT_BYTE_ARRAY);
|
||||
|
||||
assertEquals(Float.floatToIntBits(FLOAT_VALUE), Float.floatToIntBits(value));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGuava_whenConvertingFloatToByteArray_thenSuccess() {
|
||||
byte[] bytes = convertFloatToByteArrayUsingGuava(FLOAT_VALUE);
|
||||
|
||||
assertArrayEquals(FLOAT_BYTE_ARRAY, bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGuava_whenConvertingByteArrayToDouble_thenSuccess() {
|
||||
double value = convertByteArrayToDoubleUsingGuava(DOUBLE_BYTE_ARRAY);
|
||||
|
||||
assertEquals(Double.doubleToLongBits(DOUBLE_VALUE), Double.doubleToLongBits(value));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGuava_whenConvertingDoubleToByteArray_thenSuccess() {
|
||||
byte[] bytes = convertDoubleToByteArrayUsingGuava(DOUBLE_VALUE);
|
||||
|
||||
assertArrayEquals(DOUBLE_BYTE_ARRAY, bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCommonsLang_whenConvertingByteArrayToInt_thenSuccess() {
|
||||
int value = convertByteArrayToIntUsingCommonsLang(INT_BYTE_ARRAY);
|
||||
|
||||
assertEquals(INT_VALUE, value);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCommonsLang_whenConvertingIntToByteArray_thenSuccess() {
|
||||
byte[] bytes = convertIntToByteArrayUsingCommonsLang(INT_VALUE);
|
||||
|
||||
assertArrayEquals(INT_BYTE_ARRAY, bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCommonsLang_whenConvertingByteArrayToLong_thenSuccess() {
|
||||
long value = convertByteArrayToLongUsingCommonsLang(LONG_BYTE_ARRAY);
|
||||
|
||||
assertEquals(LONG_VALUE, value);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCommonsLang_whenConvertingLongToByteArray_thenSuccess() {
|
||||
byte[] bytes = convertLongToByteArrayUsingCommonsLang(LONG_VALUE);
|
||||
|
||||
assertArrayEquals(LONG_BYTE_ARRAY, bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCommonsLang_whenConvertingByteArrayToFloat_thenSuccess() {
|
||||
float value = convertByteArrayToFloatUsingCommonsLang(FLOAT_BYTE_ARRAY);
|
||||
|
||||
assertEquals(Float.floatToIntBits(FLOAT_VALUE), Float.floatToIntBits(value));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCommonsLang_whenConvertingFloatToByteArray_thenSuccess() {
|
||||
byte[] bytes = convertFloatToByteArrayUsingCommonsLang(FLOAT_VALUE);
|
||||
|
||||
assertArrayEquals(FLOAT_BYTE_ARRAY, bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCommonsLang_whenConvertingByteArrayToDouble_thenSuccess() {
|
||||
double value = convertByteArrayToDoubleUsingCommonsLang(DOUBLE_BYTE_ARRAY);
|
||||
|
||||
assertEquals(Double.doubleToLongBits(DOUBLE_VALUE), Double.doubleToLongBits(value));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCommonsLang_whenConvertingDoubleToByteArray_thenSuccess() {
|
||||
byte[] bytes = convertDoubleToByteArrayUsingCommonsLang(DOUBLE_VALUE);
|
||||
|
||||
assertArrayEquals(DOUBLE_BYTE_ARRAY, bytes);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -10,3 +10,4 @@ This module contains articles about advanced operations on arrays in Java. They
|
||||
- [Intersection Between two Integer Arrays](https://www.baeldung.com/java-array-intersection)
|
||||
- [Comparing Arrays in Java](https://www.baeldung.com/java-comparing-arrays)
|
||||
- [Concatenate Two Arrays in Java](https://www.baeldung.com/java-concatenate-arrays)
|
||||
- [Performance of System.arraycopy() vs. Arrays.copyOf()](https://www.baeldung.com/java-system-arraycopy-arrays-copyof-performance)
|
||||
|
||||
@@ -26,10 +26,50 @@
|
||||
<version>${assertj-core.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>${jmh.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${jmh.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<assertj-core.version>3.10.0</assertj-core.version>
|
||||
<jmh.version>1.33</jmh.version>
|
||||
</properties>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-assembly-plugin</artifactId>
|
||||
<configuration>
|
||||
<descriptorRefs>
|
||||
<descriptorRef>jar-with-dependencies</descriptorRef>
|
||||
</descriptorRefs>
|
||||
<archive>
|
||||
<manifest>
|
||||
<mainClass>com.baeldung.copyarraymethodsperformance.BenchmarkRunner</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>make-assembly</id>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>single</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.copyarraymethodsperformance;
|
||||
|
||||
public class BenchmarkRunner {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
|
||||
org.openjdk.jmh.Main.main(args);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package com.baeldung.copyarraymethodsperformance;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@State(Scope.Thread)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
@Warmup(iterations = 10)
|
||||
@Fork(1)
|
||||
@Measurement(iterations = 100)
|
||||
public class ObjectsCopyBenchmark {
|
||||
|
||||
@Param({ "10", "1000000" })
|
||||
public int SIZE;
|
||||
Integer[] src;
|
||||
|
||||
@Setup
|
||||
public void setup() {
|
||||
Random r = new Random();
|
||||
src = new Integer[SIZE];
|
||||
|
||||
for (int i = 0; i < SIZE; i++) {
|
||||
src[i] = r.nextInt();
|
||||
}
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public Integer[] systemArrayCopyBenchmark() {
|
||||
Integer[] target = new Integer[SIZE];
|
||||
System.arraycopy(src, 0, target, 0, SIZE);
|
||||
return target;
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public Integer[] arraysCopyOfBenchmark() {
|
||||
return Arrays.copyOf(src, SIZE);
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.copyarraymethodsperformance;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@State(Scope.Thread)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
@Warmup(iterations = 10)
|
||||
@Fork(1)
|
||||
@Measurement(iterations = 100)
|
||||
public class PrimitivesCopyBenchmark {
|
||||
|
||||
@Param({ "10", "1000000" })
|
||||
public int SIZE;
|
||||
|
||||
int[] src;
|
||||
|
||||
@Setup
|
||||
public void setup() {
|
||||
Random r = new Random();
|
||||
src = new int[SIZE];
|
||||
|
||||
for (int i = 0; i < SIZE; i++) {
|
||||
src[i] = r.nextInt();
|
||||
}
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public int[] systemArrayCopyBenchmark() {
|
||||
int[] target = new int[SIZE];
|
||||
System.arraycopy(src, 0, target, 0, SIZE);
|
||||
return target;
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public int[] arraysCopyOfBenchmark() {
|
||||
return Arrays.copyOf(src, SIZE);
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,6 @@
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
@@ -78,4 +77,5 @@
|
||||
<guava.version>28.2-jre</guava.version>
|
||||
<assertj-core.version>3.10.0</assertj-core.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -7,12 +7,11 @@
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-char</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
@@ -6,12 +6,11 @@
|
||||
<artifactId>core-java-collections-2</artifactId>
|
||||
<name>core-java-collections-2</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
@@ -44,7 +43,7 @@
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-runner</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<version>${junit-platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
@@ -53,7 +52,6 @@
|
||||
<eclipse.collections.version>7.1.0</eclipse.collections.version>
|
||||
<commons-collections4.version>4.1</commons-collections4.version>
|
||||
<assertj.version>3.11.1</assertj.version>
|
||||
<junit.platform.version>1.2.0</junit.platform.version>
|
||||
<commons-exec.version>1.3</commons-exec.version>
|
||||
</properties>
|
||||
|
||||
|
||||
@@ -7,12 +7,11 @@
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-collections-3</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
@@ -1,31 +1,30 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-collections-4</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-collections-4</name>
|
||||
<packaging>jar</packaging>
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-collections-4</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-collections-4</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<assertj.version>3.19.0</assertj.version>
|
||||
</properties>
|
||||
<properties>
|
||||
<assertj.version>3.19.0</assertj.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -12,7 +12,6 @@
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
@@ -8,5 +8,5 @@ This module contains articles about Map data structures in Java.
|
||||
- [The Map.computeIfAbsent() Method](https://www.baeldung.com/java-map-computeifabsent)
|
||||
- [Collections.synchronizedMap vs. ConcurrentHashMap](https://www.baeldung.com/java-synchronizedmap-vs-concurrenthashmap)
|
||||
- [Java HashMap Load Factor](https://www.baeldung.com/java-hashmap-load-factor)
|
||||
- [Converting java.util.Properties to HashMap](https://www.baeldung.com/java-convert-properties-to-hashmap)
|
||||
- [Converting Java Properties to HashMap](https://www.baeldung.com/java-convert-properties-to-hashmap)
|
||||
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-2)
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package com.baeldung.map.hashmap.entryremoval;
|
||||
|
||||
import java.util.ConcurrentModificationException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
public class RemoveEntryApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
HashMap<String, String> foodItemTypeMap = new HashMap<>();
|
||||
foodItemTypeMap.put("Apple", "Fruit");
|
||||
foodItemTypeMap.put("Grape", "Fruit");
|
||||
foodItemTypeMap.put("Mango", "Fruit");
|
||||
foodItemTypeMap.put("Carrot", "Vegetable");
|
||||
foodItemTypeMap.put("Potato", "Vegetable");
|
||||
foodItemTypeMap.put("Spinach", "Vegetable");
|
||||
// Current Map Status: {Potato=Vegetable, Apple=Fruit, Carrot=Vegetable, Grape=Fruit, Mango=Fruit, Spinach=Vegetable}
|
||||
|
||||
foodItemTypeMap.remove("Apple");
|
||||
// Current Map Status: {Potato=Vegetable, Carrot=Vegetable, Grape=Fruit, Mango=Fruit, Spinach=Vegetable}
|
||||
|
||||
foodItemTypeMap.remove("Grape", "Vegetable");
|
||||
// Current Map Status: {Potato=Vegetable, Carrot=Vegetable, Grape=Fruit, Mango=Fruit, Spinach=Vegetable}
|
||||
|
||||
try {
|
||||
for (Entry<String, String> item : foodItemTypeMap.entrySet()) {
|
||||
if (item.getKey()
|
||||
.equals("Potato")) {
|
||||
foodItemTypeMap.remove(item.getKey());
|
||||
}
|
||||
}
|
||||
} catch (ConcurrentModificationException e) {
|
||||
System.out.println("Exception occured while updating map: " + e.toString());
|
||||
}
|
||||
|
||||
foodItemTypeMap.entrySet()
|
||||
.removeIf(entry -> entry.getKey()
|
||||
.equals("Grape"));
|
||||
// Current Map Status: {Carrot=Vegetable, Mango=Fruit, Spinach=Vegetable}
|
||||
|
||||
Iterator<Entry<String, String>> iterator = foodItemTypeMap.entrySet()
|
||||
.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
if (iterator.next()
|
||||
.getKey()
|
||||
.equals("Carrot"))
|
||||
iterator.remove();
|
||||
}
|
||||
// Current Map Status: {Mango=Fruit, Spinach=Vegetable}
|
||||
|
||||
// Use ConcurrentHashMap
|
||||
ConcurrentHashMap<String, String> foodItemTypeConcMap = new ConcurrentHashMap<>();
|
||||
foodItemTypeConcMap.put("Apple", "Fruit");
|
||||
foodItemTypeConcMap.put("Grape", "Fruit");
|
||||
foodItemTypeConcMap.put("Mango", "Fruit");
|
||||
foodItemTypeConcMap.put("Carrot", "Vegetable");
|
||||
foodItemTypeConcMap.put("Potato", "Vegetable");
|
||||
foodItemTypeConcMap.put("Spinach", "Vegetable");
|
||||
|
||||
for (Entry<String, String> item : foodItemTypeConcMap.entrySet()) {
|
||||
if (item.getKey() != null && item.getKey()
|
||||
.equals("Potato")) {
|
||||
foodItemTypeConcMap.remove(item.getKey());
|
||||
}
|
||||
}
|
||||
|
||||
// foodItemTypeConcMap : {Apple=Fruit, Carrot=Vegetable, Grape=Fruit, Mango=Fruit, Spinach=Vegetable}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
## Java Collections Cookbooks and Examples
|
||||
|
||||
This module contains articles about Map data structures in Java.
|
||||
|
||||
### Relevant Articles:
|
||||
- [Using a Custom Class as a Key in a Java HashMap](https://www.baeldung.com/java-custom-class-map-key)
|
||||
@@ -0,0 +1,34 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-collections-maps-4</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-collections-maps-4</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<build>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>3.0.0-M5</version>
|
||||
<configuration>
|
||||
<!-- those tests are not made for CI purposes, but for manual testing -->
|
||||
<groups>!performance</groups>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.maps;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public class CoordinateKey {
|
||||
|
||||
private final int x;
|
||||
private final int y;
|
||||
private final int hashCode;
|
||||
|
||||
public CoordinateKey(int x, int y) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
this.hashCode = Objects.hash(x, y);
|
||||
}
|
||||
|
||||
public int getX() {
|
||||
return x;
|
||||
}
|
||||
|
||||
public int getY() {
|
||||
return y;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o)
|
||||
return true;
|
||||
if (o == null || getClass() != o.getClass())
|
||||
return false;
|
||||
CoordinateKey that = (CoordinateKey) o;
|
||||
return x == that.x && y == that.y;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return this.hashCode;
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.maps;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public class CoordinateMutableKey {
|
||||
|
||||
private int x;
|
||||
private int y;
|
||||
|
||||
public CoordinateMutableKey(int x, int y) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
}
|
||||
|
||||
public int getX() {
|
||||
return x;
|
||||
}
|
||||
|
||||
public void setX(int x) {
|
||||
this.x = x;
|
||||
}
|
||||
|
||||
public int getY() {
|
||||
return y;
|
||||
}
|
||||
|
||||
public void setY(int y) {
|
||||
this.y = y;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o)
|
||||
return true;
|
||||
if (o == null || getClass() != o.getClass())
|
||||
return false;
|
||||
CoordinateMutableKey that = (CoordinateMutableKey) o;
|
||||
return x == that.x && y == that.y;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(x, y);
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.maps;
|
||||
|
||||
public class CoordinateSlowKey extends CoordinateKey {
|
||||
|
||||
public CoordinateSlowKey(int x, int y) {
|
||||
super(x, y);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
package com.baeldung.maps;
|
||||
|
||||
import org.junit.jupiter.api.Tag;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.awt.*;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
||||
public class CoordinateKeyUnitTest {
|
||||
|
||||
private Map<CoordinateKey, Color> pixels = new HashMap<>();
|
||||
|
||||
@Test
|
||||
void testOptimalKey() {
|
||||
// setup
|
||||
CoordinateKey coord = new CoordinateKey(1, 2);
|
||||
pixels.put(coord, Color.CYAN);
|
||||
// read out color correctly
|
||||
assertEquals(Color.CYAN, pixels.get(coord));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSlowKey() {
|
||||
// setup
|
||||
CoordinateKey coord = new CoordinateSlowKey(1, 2);
|
||||
pixels.put(coord, Color.CYAN);
|
||||
// read out color correctly
|
||||
assertEquals(Color.CYAN, pixels.get(coord));
|
||||
}
|
||||
|
||||
// Performance Test Parameters - change here
|
||||
private static final int MAX_X = 100;
|
||||
private static final int MAX_Y = 100;
|
||||
private static final int COUNT_OF_QUERIES = 1000;
|
||||
private static final int QUERY_X = 1;
|
||||
private static final int QUERY_Y = 1;
|
||||
|
||||
@Tag("performance")
|
||||
@Test
|
||||
void testKeyPerformance() {
|
||||
// generate some sample keys and values
|
||||
for (int x = 0; x < MAX_X; x++) {
|
||||
for (int y = 0; y < MAX_Y; y++) {
|
||||
pixels.put(new CoordinateKey(x, y), new Color(x % 255, y % 255, (x + y) % 255));
|
||||
}
|
||||
}
|
||||
// read out multiple times and measure time
|
||||
CoordinateKey coord = new CoordinateKey(QUERY_X, QUERY_Y);
|
||||
long t1 = System.currentTimeMillis();
|
||||
for (int i = 0; i < COUNT_OF_QUERIES; i++) {
|
||||
assertNotNull(pixels.get(coord));
|
||||
}
|
||||
long t2 = System.currentTimeMillis();
|
||||
System.out.printf("Optimal key performance: %d ms%n", t2 - t1);
|
||||
}
|
||||
|
||||
@Tag("performance")
|
||||
@Test
|
||||
void testSlowKeyPerformance() {
|
||||
// generate some sample keys and values
|
||||
for (int x = 0; x < MAX_X; x++) {
|
||||
for (int y = 0; y < MAX_Y; y++) {
|
||||
pixels.put(new CoordinateSlowKey(x, y), new Color(x % 255, y % 255, (x + y) % 255));
|
||||
}
|
||||
}
|
||||
// read out multiple times and measure time
|
||||
CoordinateKey coord = new CoordinateSlowKey(QUERY_X, QUERY_Y);
|
||||
long t1 = System.currentTimeMillis();
|
||||
for (int i = 0; i < COUNT_OF_QUERIES; i++) {
|
||||
assertNotNull(pixels.get(coord));
|
||||
}
|
||||
long t2 = System.currentTimeMillis();
|
||||
System.out.printf("Slow key performance: %d ms%n", t2 - t1);
|
||||
}
|
||||
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.maps;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.awt.*;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
|
||||
public class CoordinateMutableKeyUnitTest {
|
||||
|
||||
@Test
|
||||
void testKeyMutable() {
|
||||
// setup
|
||||
Map<CoordinateMutableKey, Color> pixels = new HashMap<>();
|
||||
CoordinateMutableKey coord = new CoordinateMutableKey(1, 2);
|
||||
pixels.put(coord, Color.CYAN);
|
||||
// read out color correctly
|
||||
assertEquals(Color.CYAN, pixels.get(coord));
|
||||
// change key's hashcode should result in null value
|
||||
coord.setX(10);
|
||||
assertNull(pixels.get(coord));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -12,7 +12,6 @@
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
@@ -33,5 +32,5 @@
|
||||
<commons-collections4.version>4.1</commons-collections4.version>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
</project>
|
||||
@@ -7,12 +7,11 @@
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-collections</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
@@ -12,14 +12,12 @@
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<groupId>org.junit.vintage</groupId>
|
||||
<artifactId>junit-vintage-engine</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@@ -97,7 +95,6 @@
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<junit.version>4.13</junit.version>
|
||||
<threadweaver.version>0.2</threadweaver.version>
|
||||
<tempus-fugit.version>1.1</tempus-fugit.version>
|
||||
<multithreadedtc.version>1.01</multithreadedtc.version>
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<build>
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
@@ -11,7 +11,6 @@
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
@@ -3,6 +3,6 @@
|
||||
### Relevant Articles:
|
||||
|
||||
- [Read and Write User Input in Java](http://www.baeldung.com/java-console-input-output)
|
||||
- [Formatting with printf() in Java](https://www.baeldung.com/java-printstream-printf)
|
||||
- [Formatting Output with printf() in Java](https://www.baeldung.com/java-printstream-printf)
|
||||
- [ASCII Art in Java](http://www.baeldung.com/ascii-art-in-java)
|
||||
- [System.console() vs. System.out](https://www.baeldung.com/java-system-console-vs-system-out)
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user