Merge branch 'master' into master
This commit is contained in:
commit
9e1c9ee99a
|
@ -4,7 +4,7 @@ before_install:
|
|||
- echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:+CMSClassUnloadingEnabled -XX:+UseG1GC -XX:-UseGCOverheadLimit'" > ~/.mavenrc
|
||||
|
||||
install: skip
|
||||
script: travis_wait 60 mvn -q install -Pdefault-first,default-second
|
||||
script: travis_wait 60 mvn -q install -Pdefault-first,default-second -Dgib.enabled=true
|
||||
|
||||
sudo: required
|
||||
|
||||
|
|
|
@ -1,10 +1,10 @@
|
|||
<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>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>algorithms-genetic</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
|
||||
<name>algorithms-genetic</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
|
@ -61,4 +61,5 @@
|
|||
<commons-codec.version>1.11</commons-codec.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -1,10 +1,10 @@
|
|||
<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>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>algorithms-miscellaneous-1</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
|
||||
<name>algorithms-miscellaneous-1</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
|
@ -17,6 +17,11 @@
|
|||
<artifactId>commons-math3</artifactId>
|
||||
<version>${commons-math3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-codec</groupId>
|
||||
<artifactId>commons-codec</artifactId>
|
||||
|
@ -73,6 +78,7 @@
|
|||
<commons-math3.version>3.6.1</commons-math3.version>
|
||||
<org.assertj.core.version>3.9.0</org.assertj.core.version>
|
||||
<commons-codec.version>1.11</commons-codec.version>
|
||||
<guava.version>25.1-jre</guava.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,63 @@
|
|||
package com.baeldung.algorithms.factorial;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.stream.LongStream;
|
||||
|
||||
import org.apache.commons.math3.util.CombinatoricsUtils;
|
||||
|
||||
import com.google.common.math.BigIntegerMath;
|
||||
|
||||
public class Factorial {
|
||||
|
||||
public long factorialUsingForLoop(int n) {
|
||||
long fact = 1;
|
||||
for (int i = 2; i <= n; i++) {
|
||||
fact = fact * i;
|
||||
}
|
||||
return fact;
|
||||
}
|
||||
|
||||
public long factorialUsingStreams(int n) {
|
||||
return LongStream.rangeClosed(1, n)
|
||||
.reduce(1, (long x, long y) -> x * y);
|
||||
}
|
||||
|
||||
public long factorialUsingRecursion(int n) {
|
||||
if (n <= 2) {
|
||||
return n;
|
||||
}
|
||||
return n * factorialUsingRecursion(n - 1);
|
||||
}
|
||||
|
||||
private Long[] factorials = new Long[20];
|
||||
|
||||
public long factorialUsingMemoize(int n) {
|
||||
|
||||
if (factorials[n] != null) {
|
||||
return factorials[n];
|
||||
}
|
||||
|
||||
if (n <= 2) {
|
||||
return n;
|
||||
}
|
||||
long nthValue = n * factorialUsingMemoize(n - 1);
|
||||
factorials[n] = nthValue;
|
||||
return nthValue;
|
||||
}
|
||||
|
||||
public BigInteger factorialHavingLargeResult(int n) {
|
||||
BigInteger result = BigInteger.ONE;
|
||||
for (int i = 2; i <= n; i++)
|
||||
result = result.multiply(BigInteger.valueOf(i));
|
||||
return result;
|
||||
}
|
||||
|
||||
public long factorialUsingApacheCommons(int n) {
|
||||
return CombinatoricsUtils.factorial(n);
|
||||
}
|
||||
|
||||
public BigInteger factorialUsingGuava(int n) {
|
||||
return BigIntegerMath.factorial(n);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,72 @@
|
|||
package com.baeldung.algorithms.factorial;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.math.BigInteger;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class FactorialUnitTest {
|
||||
|
||||
Factorial factorial;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
factorial = new Factorial();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCalculatingFactorialUsingForLoop_thenCorrect() {
|
||||
int n = 5;
|
||||
|
||||
assertThat(factorial.factorialUsingForLoop(n)).isEqualTo(120);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCalculatingFactorialUsingStreams_thenCorrect() {
|
||||
int n = 5;
|
||||
|
||||
assertThat(factorial.factorialUsingStreams(n)).isEqualTo(120);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCalculatingFactorialUsingRecursion_thenCorrect() {
|
||||
int n = 5;
|
||||
|
||||
assertThat(factorial.factorialUsingRecursion(n)).isEqualTo(120);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCalculatingFactorialUsingMemoize_thenCorrect() {
|
||||
int n = 5;
|
||||
|
||||
assertThat(factorial.factorialUsingMemoize(n)).isEqualTo(120);
|
||||
|
||||
n = 6;
|
||||
|
||||
assertThat(factorial.factorialUsingMemoize(n)).isEqualTo(720);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCalculatingFactorialHavingLargeResult_thenCorrect() {
|
||||
int n = 22;
|
||||
|
||||
assertThat(factorial.factorialHavingLargeResult(n)).isEqualTo(new BigInteger("1124000727777607680000"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCalculatingFactorialUsingApacheCommons_thenCorrect() {
|
||||
int n = 5;
|
||||
|
||||
assertThat(factorial.factorialUsingApacheCommons(n)).isEqualTo(120);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCalculatingFactorialUsingGuava_thenCorrect() {
|
||||
int n = 22;
|
||||
|
||||
assertThat(factorial.factorialUsingGuava(n)).isEqualTo(new BigInteger("1124000727777607680000"));
|
||||
}
|
||||
|
||||
}
|
|
@ -17,3 +17,4 @@
|
|||
- [Round Up to the Nearest Hundred](https://www.baeldung.com/java-round-up-nearest-hundred)
|
||||
- [Calculate Percentage in Java](https://www.baeldung.com/java-calculate-percentage)
|
||||
- [Converting Between Byte Arrays and Hexadecimal Strings in Java](https://www.baeldung.com/java-byte-arrays-hex-strings)
|
||||
- [Convert Latitude and Longitude to a 2D Point in Java](https://www.baeldung.com/java-convert-latitude-longitude)
|
||||
|
|
|
@ -1,9 +1,9 @@
|
|||
<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>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>algorithms-miscellaneous-2</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>algorithms-miscellaneous-2</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
|
|
|
@ -1,9 +1,9 @@
|
|||
<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>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>algorithms-sorting</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>algorithms-sorting</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
|
|
|
@ -3,7 +3,8 @@
|
|||
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>annotation-processing</artifactId>
|
||||
|
||||
<name>annotation-processing</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
|
|
|
@ -3,6 +3,7 @@
|
|||
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>annotation-user</artifactId>
|
||||
<name>annotation-user</name>
|
||||
|
||||
<parent>
|
||||
<artifactId>annotations</artifactId>
|
||||
|
|
|
@ -4,7 +4,8 @@
|
|||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>annotations</artifactId>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<name>annotations</name>
|
||||
|
||||
<parent>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
|
|
|
@ -3,10 +3,9 @@
|
|||
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>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>apache-avro</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>Apache Avro</name>
|
||||
<name>apache-avro</name>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
|
|
|
@ -4,7 +4,8 @@
|
|||
<groupId>apache-bval</groupId>
|
||||
<artifactId>apache-bval</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
|
||||
<name>apache-bval</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
|
|
|
@ -4,6 +4,7 @@
|
|||
<artifactId>apache-curator</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>apache-curator</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
|
|
|
@ -2,7 +2,8 @@
|
|||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>cxf-aegis</artifactId>
|
||||
|
||||
<name>cxf-aegis</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>apache-cxf</artifactId>
|
||||
|
|
|
@ -4,7 +4,8 @@
|
|||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>cxf-introduction</artifactId>
|
||||
|
||||
<name>cxf-introduction</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>apache-cxf</artifactId>
|
||||
|
|
|
@ -4,7 +4,8 @@
|
|||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>cxf-jaxrs-implementation</artifactId>
|
||||
|
||||
<name>cxf-jaxrs-implementation</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>apache-cxf</artifactId>
|
||||
|
|
|
@ -3,6 +3,7 @@
|
|||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>cxf-spring</artifactId>
|
||||
<packaging>war</packaging>
|
||||
<name>cxf-spring</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
|
|
|
@ -1,9 +1,9 @@
|
|||
<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>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>apache-cxf</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>apache-cxf</name>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<parent>
|
||||
|
|
|
@ -3,8 +3,8 @@
|
|||
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>sse-jaxrs</artifactId>
|
||||
<name>sse-jaxrs</name>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<parent>
|
||||
|
|
|
@ -3,15 +3,15 @@
|
|||
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>sse-jaxrs-client</artifactId>
|
||||
<name>sse-jaxrs-client</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>sse-jaxrs</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>sse-jaxrs-client</artifactId>
|
||||
|
||||
<properties>
|
||||
<cxf-version>3.2.0</cxf-version>
|
||||
</properties>
|
||||
|
@ -21,7 +21,6 @@
|
|||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>1.6.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>singleEvent</id>
|
||||
|
|
|
@ -3,16 +3,16 @@
|
|||
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>sse-jaxrs-server</artifactId>
|
||||
<name>sse-jaxrs-server</name>
|
||||
<packaging>war</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>sse-jaxrs</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>sse-jaxrs-server</artifactId>
|
||||
<packaging>war</packaging>
|
||||
|
||||
<properties>
|
||||
<liberty-maven-plugin.version>2.4.2</liberty-maven-plugin.version>
|
||||
<failOnMissingWebXml>false</failOnMissingWebXml>
|
||||
|
|
|
@ -3,11 +3,10 @@
|
|||
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>
|
||||
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>apache-geode</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
|
||||
<name>apache-geode</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
|
|
|
@ -4,6 +4,7 @@
|
|||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>apache-opennlp</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<name>apache-opennlp</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
|
|
|
@ -1,9 +1,9 @@
|
|||
<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>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>apache-poi</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>apache-poi</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
|
|
|
@ -1,21 +1,22 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung.pulsar</groupId>
|
||||
<artifactId>pulsar-java</artifactId>
|
||||
<version>0.0.1</version>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung.pulsar</groupId>
|
||||
<artifactId>apache-pulsar</artifactId>
|
||||
<version>0.0.1</version>
|
||||
<name>apache-pulsar</name>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.pulsar</groupId>
|
||||
<artifactId>pulsar-client</artifactId>
|
||||
<version>2.1.1-incubating</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<properties>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.pulsar</groupId>
|
||||
<artifactId>pulsar-client</artifactId>
|
||||
<version>2.1.1-incubating</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<properties>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
</properties>
|
||||
</project>
|
||||
|
|
|
@ -5,7 +5,8 @@
|
|||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>apache-shiro</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
|
||||
<name>apache-shiro</name>
|
||||
|
||||
<parent>
|
||||
<artifactId>parent-boot-1</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
|
|
|
@ -1,9 +1,9 @@
|
|||
<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>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>apache-thrift</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>apache-thrift</name>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<parent>
|
||||
|
|
|
@ -1,10 +1,10 @@
|
|||
<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>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>apache-tika</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
|
||||
<name>apache-tika</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
|
|
|
@ -1,9 +1,9 @@
|
|||
<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>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>apache-zookeeper</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>apache-zookeeper</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
|
|
|
@ -5,6 +5,7 @@
|
|||
<groupId>com.baeldung.examples</groupId>
|
||||
<artifactId>asm</artifactId>
|
||||
<version>1.0</version>
|
||||
<name>asm</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
|
|
|
@ -4,7 +4,8 @@
|
|||
<groupId>com.atomix.io</groupId>
|
||||
<artifactId>atomix</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
|
||||
<name>atomix</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
|
|
|
@ -3,7 +3,8 @@
|
|||
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>axon</artifactId>
|
||||
|
||||
<name>axon</name>
|
||||
|
||||
<parent>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
|
|
|
@ -3,8 +3,9 @@
|
|||
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>cas-server</artifactId>
|
||||
<packaging>war</packaging>
|
||||
<version>1.0</version>
|
||||
<name>cas-server</name>
|
||||
<packaging>war</packaging>
|
||||
|
||||
<parent>
|
||||
<artifactId>parent-boot-1</artifactId>
|
||||
|
|
|
@ -1,3 +1,5 @@
|
|||
### Relevant Articles:
|
||||
- [CDI Interceptor vs Spring AspectJ](http://www.baeldung.com/cdi-interceptor-vs-spring-aspectj)
|
||||
- [An Introduction to CDI (Contexts and Dependency Injection) in Java](http://www.baeldung.com/java-ee-cdi)
|
||||
- [Introduction to the Event Notification Model in CDI 2.0](https://www.baeldung.com/cdi-event-notification)
|
||||
|
||||
|
|
27
cdi/pom.xml
27
cdi/pom.xml
|
@ -2,10 +2,10 @@
|
|||
<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>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>cdi</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
|
||||
<name>cdi</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-spring-4</artifactId>
|
||||
|
@ -14,6 +14,16 @@
|
|||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>javax.enterprise</groupId>
|
||||
<artifactId>cdi-api</artifactId>
|
||||
<version>${cdi-api.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jboss.weld.se</groupId>
|
||||
<artifactId>weld-se-core</artifactId>
|
||||
<version>${weld-se-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-core</artifactId>
|
||||
|
@ -42,11 +52,6 @@
|
|||
<artifactId>aspectjweaver</artifactId>
|
||||
<version>${aspectjweaver.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jboss.weld.se</groupId>
|
||||
<artifactId>weld-se-core</artifactId>
|
||||
<version>${weld-se-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
|
@ -54,13 +59,13 @@
|
|||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<aspectjweaver.version>1.8.9</aspectjweaver.version>
|
||||
<weld-se-core.version>2.4.1.Final</weld-se-core.version>
|
||||
<cdi-api.version>2.0.SP1</cdi-api.version>
|
||||
<weld-se-core.version>3.0.5.Final</weld-se-core.version>
|
||||
<aspectjweaver.version>1.9.2</aspectjweaver.version>
|
||||
<hamcrest-core.version>1.3</hamcrest-core.version>
|
||||
<assertj-core.version>3.10.0</assertj-core.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<spring.version>5.1.2.RELEASE</spring.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -0,0 +1,15 @@
|
|||
package com.baeldung.cdi.cdi2observers.application;
|
||||
|
||||
import com.baeldung.cdi.cdi2observers.events.ExampleEvent;
|
||||
import javax.enterprise.inject.se.SeContainer;
|
||||
import javax.enterprise.inject.se.SeContainerInitializer;
|
||||
|
||||
public class BootstrappingApplication {
|
||||
|
||||
public static void main(String... args) {
|
||||
SeContainerInitializer containerInitializer = SeContainerInitializer.newInstance();
|
||||
try (SeContainer container = containerInitializer.initialize()) {
|
||||
container.getBeanManager().fireEvent(new ExampleEvent("Welcome to Baeldung!"));
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package com.baeldung.cdi.cdi2observers.events;
|
||||
|
||||
public class ExampleEvent {
|
||||
|
||||
private final String eventMessage;
|
||||
|
||||
public ExampleEvent(String eventMessage) {
|
||||
this.eventMessage = eventMessage;
|
||||
}
|
||||
|
||||
public String getEventMessage() {
|
||||
return eventMessage;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package com.baeldung.cdi.cdi2observers.events;
|
||||
|
||||
import javax.enterprise.event.Event;
|
||||
import javax.inject.Inject;
|
||||
|
||||
public class ExampleEventSource {
|
||||
|
||||
@Inject
|
||||
Event<ExampleEvent> exampleEvent;
|
||||
|
||||
public void fireEvent() {
|
||||
exampleEvent.fireAsync(new ExampleEvent("Welcome to Baeldung!"));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,12 @@
|
|||
package com.baeldung.cdi.cdi2observers.observers;
|
||||
|
||||
import com.baeldung.cdi.cdi2observers.events.ExampleEvent;
|
||||
import javax.annotation.Priority;
|
||||
import javax.enterprise.event.Observes;
|
||||
|
||||
public class AnotherExampleEventObserver {
|
||||
|
||||
public String onEvent(@Observes @Priority(2) ExampleEvent event) {
|
||||
return event.getEventMessage();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
package com.baeldung.cdi.cdi2observers.observers;
|
||||
|
||||
import com.baeldung.cdi.cdi2observers.events.ExampleEvent;
|
||||
import com.baeldung.cdi.cdi2observers.services.TextService;
|
||||
import javax.annotation.Priority;
|
||||
import javax.enterprise.event.Observes;
|
||||
|
||||
public class ExampleEventObserver {
|
||||
|
||||
public String onEvent(@Observes @Priority(1) ExampleEvent event, TextService textService) {
|
||||
return textService.parseText(event.getEventMessage());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
package com.baeldung.cdi.cdi2observers.services;
|
||||
|
||||
public class TextService {
|
||||
|
||||
public String parseText(String text) {
|
||||
return text.toUpperCase();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package com.baeldung.cdi.cdi2observers.tests;
|
||||
|
||||
import com.baeldung.cdi.cdi2observers.services.TextService;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class TextServiceUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenTextServiceInstance_whenCalledparseText_thenCorrect() {
|
||||
TextService textService = new TextService();
|
||||
assertThat(textService.parseText("Baeldung")).isEqualTo("BAELDUNG");
|
||||
}
|
||||
}
|
|
@ -4,6 +4,7 @@
|
|||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-groovy</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<name>core-groovy</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
|
|
|
@ -4,3 +4,4 @@
|
|||
- [Java 10 LocalVariable Type-Inference](http://www.baeldung.com/java-10-local-variable-type-inference)
|
||||
- [Guide to Java 10](http://www.baeldung.com/java-10-overview)
|
||||
- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)
|
||||
- [Deep Dive Into the New Java JIT Compiler – Graal](https://www.baeldung.com/graal-java-jit-compiler)
|
||||
|
|
|
@ -33,3 +33,4 @@
|
|||
- [An Overview of Regular Expressions Performance in Java](https://www.baeldung.com/java-regex-performance)
|
||||
- [Java Primitives versus Objects](https://www.baeldung.com/java-primitives-vs-objects)
|
||||
- [How to Use if/else Logic in Java 8 Streams](https://www.baeldung.com/java-8-streams-if-else-logic)
|
||||
- [How to Replace Many if Statements in Java](https://www.baeldung.com/java-replace-if-statements)
|
||||
|
|
|
@ -1,7 +1,6 @@
|
|||
<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>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>core-java-9</artifactId>
|
||||
<version>0.2-SNAPSHOT</version>
|
||||
<name>core-java-9</name>
|
||||
|
|
|
@ -4,11 +4,13 @@ import java.lang.reflect.Array;
|
|||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.LinkedList;
|
||||
import java.util.Random;
|
||||
import java.util.Set;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.IntPredicate;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
|
||||
|
@ -194,4 +196,16 @@ public class ArrayOperations {
|
|||
public static <T> T getRandomFromObjectArray(T[] array) {
|
||||
return array[new Random().nextInt(array.length)];
|
||||
}
|
||||
|
||||
public static Integer[] intersectionSimple(final Integer[] a, final Integer[] b){
|
||||
return Stream.of(a).filter(Arrays.asList(b)::contains).toArray(Integer[]::new);
|
||||
}
|
||||
|
||||
public static Integer[] intersectionSet(final Integer[] a, final Integer[] b){
|
||||
return Stream.of(a).filter(Arrays.asList(b)::contains).distinct().toArray(Integer[]::new);
|
||||
}
|
||||
|
||||
public static Integer[] intersectionMultiSet(final Integer[] a, final Integer[] b){
|
||||
return Stream.of(a).filter(new LinkedList<>(Arrays.asList(b))::remove).toArray(Integer[]::new);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,66 @@
|
|||
package com.baeldung.array.operations;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static com.baeldung.array.operations.ArrayOperations.intersectionMultiSet;
|
||||
import static com.baeldung.array.operations.ArrayOperations.intersectionSet;
|
||||
import static com.baeldung.array.operations.ArrayOperations.intersectionSimple;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class IntersectionUnitTest {
|
||||
private static final Integer[] a = { 1, 3, 2 };
|
||||
private static final Integer[] b = { 4, 3, 2, 4, 2, 3, 4, 4, 3 };
|
||||
private static final Integer[] c = { 1, 3, 2, 3, 3, 2 };
|
||||
|
||||
@Test
|
||||
void whenIntersectionSimpleIsUsed_thenCommonEntriesAreInTheResult() {
|
||||
assertThat(intersectionSimple(a, b)).isEqualTo(new Integer[] { 3, 2 });
|
||||
assertThat(intersectionSimple(b, a)).isEqualTo(new Integer[] { 3, 2, 2, 3, 3 });
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenIntersectionSimpleIsUsedWithAnArrayAndItself_thenTheResultIsTheIdentity() {
|
||||
assertThat(intersectionSimple(b, b)).isEqualTo(b);
|
||||
assertThat(intersectionSimple(a, a)).isEqualTo(a);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenIntersectionSetIsUsed_thenCommonEntriesAreInTheResult() {
|
||||
assertThat(intersectionSet(b, a)).isEqualTo(new Integer[] { 3, 2 });
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenIntersectionSetIsUsed_thenTheNumberOfEntriesDoesNotChangeWithTheParameterOrder() {
|
||||
assertThat(intersectionSet(a, b)).isEqualTo(new Integer[] { 3, 2 });
|
||||
assertThat(intersectionSet(b, a)).isEqualTo(new Integer[] { 3, 2 });
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenIntersectionSetIsUsedWithAnArrayAndWithItself_andTheInputHasNoDuplicateEntries_ThenTheResultIsTheIdentity() {
|
||||
assertThat(intersectionSet(a, a)).isEqualTo(a);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenIntersectionSetIsUsedWithAnArrayAndWithItself_andTheInputHasDuplicateEntries_ThenTheResultIsNotTheIdentity() {
|
||||
assertThat(intersectionSet(b, b)).isNotEqualTo(b);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenMultiSetIsUsed_thenCommonEntriesAreInTheResult() {
|
||||
assertThat(intersectionMultiSet(b, a)).isEqualTo(new Integer[] { 3, 2 });
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenIntersectionMultiSetIsUsed_thenTheNumberOfEntriesDoesNotChangeWithTheParameterOrder() {
|
||||
assertThat(intersectionMultiSet(a, b)).isEqualTo(new Integer[] { 3, 2 });
|
||||
assertThat(intersectionMultiSet(b, a)).isEqualTo(new Integer[] { 3, 2 });
|
||||
assertThat(intersectionMultiSet(b, c)).isEqualTo(new Integer[] { 3, 2, 2, 3, 3 });
|
||||
assertThat(intersectionMultiSet(c, b)).isEqualTo(new Integer[] { 3, 2, 3, 3, 2 });
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenIntersectionMultiSetIsUsedWithAnArrayAndWithItself_ThenTheResultIsTheIdentity() {
|
||||
assertThat(intersectionMultiSet(b, b)).isEqualTo(b);
|
||||
assertThat(intersectionMultiSet(a, a)).isEqualTo(a);
|
||||
}
|
||||
}
|
|
@ -50,3 +50,4 @@
|
|||
- [Check If Two Lists are Equal in Java](http://www.baeldung.com/java-test-a-list-for-ordinality-and-equality)
|
||||
- [Java List Initialization in One Line](https://www.baeldung.com/java-init-list-one-line)
|
||||
- [ClassCastException: Arrays$ArrayList cannot be cast to ArrayList](https://www.baeldung.com/java-classcastexception-arrays-arraylist)
|
||||
- [A Guide to EnumMap](https://www.baeldung.com/java-enum-map)
|
||||
|
|
|
@ -0,0 +1,67 @@
|
|||
package com.baeldung.java.list;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.ListIterator;
|
||||
|
||||
/**
|
||||
* Demonstrates the different ways to loop over
|
||||
* the elements of a list.
|
||||
*/
|
||||
public class WaysToIterate {
|
||||
|
||||
List<String> countries = Arrays.asList("Germany", "Panama", "Australia");
|
||||
|
||||
/**
|
||||
* Iterate over a list using a basic for loop
|
||||
*/
|
||||
public void iterateWithForLoop() {
|
||||
for (int i = 0; i < countries.size(); i++) {
|
||||
System.out.println(countries.get(i));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate over a list using the enhanced for loop
|
||||
*/
|
||||
public void iterateWithEnhancedForLoop() {
|
||||
for (String country : countries) {
|
||||
System.out.println(country);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate over a list using an Iterator
|
||||
*/
|
||||
public void iterateWithIterator() {
|
||||
Iterator<String> countriesIterator = countries.iterator();
|
||||
while(countriesIterator.hasNext()) {
|
||||
System.out.println(countriesIterator.next());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate over a list using a ListIterator
|
||||
*/
|
||||
public void iterateWithListIterator() {
|
||||
ListIterator<String> listIterator = countries.listIterator();
|
||||
while(listIterator.hasNext()) {
|
||||
System.out.println(listIterator.next());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate over a list using the Iterable.forEach() method
|
||||
*/
|
||||
public void iterateWithForEach() {
|
||||
countries.forEach(System.out::println);
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate over a list using the Stream.forEach() method
|
||||
*/
|
||||
public void iterateWithStreamForEach() {
|
||||
countries.stream().forEach((c) -> System.out.println(c));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,71 @@
|
|||
package com.baeldung.java.list;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.ListIterator;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class WaysToIterateUnitTest {
|
||||
|
||||
List<String> globalCountries = new ArrayList<String>();
|
||||
List<String> europeanCountries = Arrays.asList("Germany", "Panama", "Australia");
|
||||
|
||||
@Test
|
||||
public void whenIteratingUsingForLoop_thenReturnThreeAsSizeOfList() {
|
||||
for (int i = 0; i < europeanCountries.size(); i++) {
|
||||
globalCountries.add(europeanCountries.get(i));
|
||||
}
|
||||
assertEquals(globalCountries.size(), 3);
|
||||
globalCountries.clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenIteratingUsingEnhancedForLoop_thenReturnThreeAsSizeOfList() {
|
||||
for (String country : europeanCountries) {
|
||||
globalCountries.add(country);
|
||||
}
|
||||
assertEquals(globalCountries.size(), 3);
|
||||
globalCountries.clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenIteratingUsingIterator_thenReturnThreeAsSizeOfList() {
|
||||
Iterator<String> countriesIterator = europeanCountries.iterator();
|
||||
while (countriesIterator.hasNext()) {
|
||||
globalCountries.add(countriesIterator.next());
|
||||
}
|
||||
|
||||
assertEquals(globalCountries.size(), 3);
|
||||
globalCountries.clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenIteratingUsingListIterator_thenReturnThreeAsSizeOfList() {
|
||||
ListIterator<String> countriesIterator = europeanCountries.listIterator();
|
||||
while (countriesIterator.hasNext()) {
|
||||
globalCountries.add(countriesIterator.next());
|
||||
}
|
||||
|
||||
assertEquals(globalCountries.size(), 3);
|
||||
globalCountries.clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenIteratingUsingForEach_thenReturnThreeAsSizeOfList() {
|
||||
europeanCountries.forEach(country -> globalCountries.add(country));
|
||||
assertEquals(globalCountries.size(), 3);
|
||||
globalCountries.clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenIteratingUsingStreamForEach_thenReturnThreeAsSizeOfList() {
|
||||
europeanCountries.stream().forEach((country) -> globalCountries.add(country));
|
||||
assertEquals(globalCountries.size(), 3);
|
||||
globalCountries.clear();
|
||||
}
|
||||
}
|
|
@ -1,34 +1,52 @@
|
|||
package com.baeldung.concurrent.Scheduledexecutorservice;
|
||||
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Function;
|
||||
|
||||
public class ScheduledExecutorServiceDemo {
|
||||
|
||||
public void execute() {
|
||||
private void execute() {
|
||||
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
|
||||
|
||||
ScheduledFuture<?> scheduledFuture = executorService.schedule(() -> {
|
||||
// Task
|
||||
}, 1, TimeUnit.SECONDS);
|
||||
|
||||
executorService.scheduleAtFixedRate(() -> {
|
||||
// Task
|
||||
}, 1, 10, TimeUnit.SECONDS);
|
||||
|
||||
executorService.scheduleWithFixedDelay(() -> {
|
||||
// Task
|
||||
}, 1, 10, TimeUnit.SECONDS);
|
||||
|
||||
Future<String> future = executorService.schedule(() -> {
|
||||
// Task
|
||||
return "Hellow world";
|
||||
}, 1, TimeUnit.SECONDS);
|
||||
|
||||
getTasksToRun().apply(executorService);
|
||||
executorService.shutdown();
|
||||
}
|
||||
|
||||
private void executeWithMultiThread() {
|
||||
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2);
|
||||
getTasksToRun().apply(executorService);
|
||||
executorService.shutdown();
|
||||
}
|
||||
|
||||
private Function<ScheduledExecutorService, Void> getTasksToRun() {
|
||||
return (executorService -> {
|
||||
ScheduledFuture<?> scheduledFuture1 = executorService.schedule(() -> {
|
||||
// Task
|
||||
}, 1, TimeUnit.SECONDS);
|
||||
|
||||
ScheduledFuture<?> scheduledFuture2 = executorService.scheduleAtFixedRate(() -> {
|
||||
// Task
|
||||
}, 1, 10, TimeUnit.SECONDS);
|
||||
|
||||
ScheduledFuture<?> scheduledFuture3 = executorService.scheduleWithFixedDelay(() -> {
|
||||
// Task
|
||||
}, 1, 10, TimeUnit.SECONDS);
|
||||
|
||||
ScheduledFuture<String> scheduledFuture4 = executorService.schedule(() -> {
|
||||
// Task
|
||||
return "Hellow world";
|
||||
}, 1, TimeUnit.SECONDS);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
public static void main(String... args) {
|
||||
ScheduledExecutorServiceDemo demo = new ScheduledExecutorServiceDemo();
|
||||
demo.execute();
|
||||
demo.executeWithMultiThread();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
|
@ -0,0 +1,33 @@
|
|||
package com.baeldung.concurrent.countdownlatch;
|
||||
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
|
||||
public class CountdownLatchCountExample {
|
||||
|
||||
private int count;
|
||||
|
||||
public CountdownLatchCountExample(int count) {
|
||||
this.count = count;
|
||||
}
|
||||
|
||||
public boolean callTwiceInSameThread() {
|
||||
CountDownLatch countDownLatch = new CountDownLatch(count);
|
||||
Thread t = new Thread(() -> {
|
||||
countDownLatch.countDown();
|
||||
countDownLatch.countDown();
|
||||
});
|
||||
t.start();
|
||||
|
||||
try {
|
||||
countDownLatch.await();
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return countDownLatch.getCount() == 0;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
CountdownLatchCountExample ex = new CountdownLatchCountExample(2);
|
||||
System.out.println("Is CountDown Completed : " + ex.callTwiceInSameThread());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,41 @@
|
|||
package com.baeldung.concurrent.countdownlatch;
|
||||
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
public class CountdownLatchResetExample {
|
||||
|
||||
private int count;
|
||||
private int threadCount;
|
||||
private final AtomicInteger updateCount;
|
||||
|
||||
CountdownLatchResetExample(int count, int threadCount) {
|
||||
updateCount = new AtomicInteger(0);
|
||||
this.count = count;
|
||||
this.threadCount = threadCount;
|
||||
}
|
||||
|
||||
public int countWaits() {
|
||||
CountDownLatch countDownLatch = new CountDownLatch(count);
|
||||
ExecutorService es = Executors.newFixedThreadPool(threadCount);
|
||||
for (int i = 0; i < threadCount; i++) {
|
||||
es.execute(() -> {
|
||||
long prevValue = countDownLatch.getCount();
|
||||
countDownLatch.countDown();
|
||||
if (countDownLatch.getCount() != prevValue) {
|
||||
updateCount.incrementAndGet();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
es.shutdown();
|
||||
return updateCount.get();
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
CountdownLatchResetExample ex = new CountdownLatchResetExample(5, 20);
|
||||
System.out.println("Count : " + ex.countWaits());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,45 @@
|
|||
package com.baeldung.concurrent.cyclicbarrier;
|
||||
|
||||
import java.util.concurrent.BrokenBarrierException;
|
||||
import java.util.concurrent.CyclicBarrier;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
public class CyclicBarrierCompletionMethodExample {
|
||||
|
||||
private int count;
|
||||
private int threadCount;
|
||||
private final AtomicInteger updateCount;
|
||||
|
||||
CyclicBarrierCompletionMethodExample(int count, int threadCount) {
|
||||
updateCount = new AtomicInteger(0);
|
||||
this.count = count;
|
||||
this.threadCount = threadCount;
|
||||
}
|
||||
|
||||
public int countTrips() {
|
||||
|
||||
CyclicBarrier cyclicBarrier = new CyclicBarrier(count, () -> {
|
||||
updateCount.incrementAndGet();
|
||||
});
|
||||
|
||||
ExecutorService es = Executors.newFixedThreadPool(threadCount);
|
||||
for (int i = 0; i < threadCount; i++) {
|
||||
es.execute(() -> {
|
||||
try {
|
||||
cyclicBarrier.await();
|
||||
} catch (InterruptedException | BrokenBarrierException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
});
|
||||
}
|
||||
es.shutdown();
|
||||
return updateCount.get();
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
CyclicBarrierCompletionMethodExample ex = new CyclicBarrierCompletionMethodExample(5, 20);
|
||||
System.out.println("Count : " + ex.countTrips());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
package com.baeldung.concurrent.cyclicbarrier;
|
||||
|
||||
import java.util.concurrent.BrokenBarrierException;
|
||||
import java.util.concurrent.CyclicBarrier;
|
||||
|
||||
public class CyclicBarrierCountExample {
|
||||
|
||||
private int count;
|
||||
|
||||
public CyclicBarrierCountExample(int count) {
|
||||
this.count = count;
|
||||
}
|
||||
|
||||
public boolean callTwiceInSameThread() {
|
||||
CyclicBarrier cyclicBarrier = new CyclicBarrier(count);
|
||||
Thread t = new Thread(() -> {
|
||||
try {
|
||||
cyclicBarrier.await();
|
||||
cyclicBarrier.await();
|
||||
} catch (InterruptedException | BrokenBarrierException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
});
|
||||
t.start();
|
||||
return cyclicBarrier.isBroken();
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
CyclicBarrierCountExample ex = new CyclicBarrierCountExample(7);
|
||||
System.out.println("Count : " + ex.callTwiceInSameThread());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,46 @@
|
|||
package com.baeldung.concurrent.cyclicbarrier;
|
||||
|
||||
import java.util.concurrent.BrokenBarrierException;
|
||||
import java.util.concurrent.CyclicBarrier;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
public class CyclicBarrierResetExample {
|
||||
|
||||
private int count;
|
||||
private int threadCount;
|
||||
private final AtomicInteger updateCount;
|
||||
|
||||
CyclicBarrierResetExample(int count, int threadCount) {
|
||||
updateCount = new AtomicInteger(0);
|
||||
this.count = count;
|
||||
this.threadCount = threadCount;
|
||||
}
|
||||
|
||||
public int countWaits() {
|
||||
|
||||
CyclicBarrier cyclicBarrier = new CyclicBarrier(count);
|
||||
|
||||
ExecutorService es = Executors.newFixedThreadPool(threadCount);
|
||||
for (int i = 0; i < threadCount; i++) {
|
||||
es.execute(() -> {
|
||||
try {
|
||||
if (cyclicBarrier.getNumberWaiting() > 0) {
|
||||
updateCount.incrementAndGet();
|
||||
}
|
||||
cyclicBarrier.await();
|
||||
} catch (InterruptedException | BrokenBarrierException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
});
|
||||
}
|
||||
es.shutdown();
|
||||
return updateCount.get();
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
CyclicBarrierResetExample ex = new CyclicBarrierResetExample(7, 20);
|
||||
System.out.println("Count : " + ex.countWaits());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,12 @@
|
|||
package com.baeldung.concurrent.daemon;
|
||||
|
||||
public class MultipleThreadsExample {
|
||||
public static void main(String[] args) {
|
||||
NewThread t1 = new NewThread();
|
||||
t1.setName("MyThread-1");
|
||||
NewThread t2 = new NewThread();
|
||||
t2.setName("MyThread-2");
|
||||
t1.start();
|
||||
t2.start();
|
||||
}
|
||||
}
|
|
@ -1,14 +1,18 @@
|
|||
package com.baeldung.concurrent.daemon;
|
||||
|
||||
public class NewThread extends Thread {
|
||||
|
||||
public void run() {
|
||||
long startTime = System.currentTimeMillis();
|
||||
while (true) {
|
||||
for (int i = 0; i < 10; i++) {
|
||||
System.out.println("New Thread is running..." + i);
|
||||
System.out.println(this.getName() + ": New Thread is running..." + i);
|
||||
try {
|
||||
//Wait for one sec so it doesn't print too fast
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
// prevent the Thread to run forever. It will finish it's execution after 2 seconds
|
||||
if (System.currentTimeMillis() - startTime > 2000) {
|
||||
Thread.currentThread().interrupt();
|
||||
|
|
|
@ -0,0 +1,8 @@
|
|||
package com.baeldung.concurrent.daemon;
|
||||
|
||||
public class SingleThreadExample {
|
||||
public static void main(String[] args) {
|
||||
NewThread t = new NewThread();
|
||||
t.start();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
package com.baeldung.concurrent.countdownlatch;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class CountdownLatchCountExampleUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenCountDownLatch_completed() {
|
||||
CountdownLatchCountExample ex = new CountdownLatchCountExample(2);
|
||||
boolean isCompleted = ex.callTwiceInSameThread();
|
||||
assertTrue(isCompleted);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
package com.baeldung.concurrent.countdownlatch;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class CountdownLatchResetExampleUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenCountDownLatch_noReset() {
|
||||
CountdownLatchResetExample ex = new CountdownLatchResetExample(7,20);
|
||||
int lineCount = ex.countWaits();
|
||||
assertTrue(lineCount <= 7);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
package com.baeldung.concurrent.cyclicbarrier;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class CyclicBarrierCompletionMethodExampleUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenCyclicBarrier_countTrips() {
|
||||
CyclicBarrierCompletionMethodExample ex = new CyclicBarrierCompletionMethodExample(7,20);
|
||||
int lineCount = ex.countTrips();
|
||||
assertEquals(2, lineCount);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
package com.baeldung.concurrent.cyclicbarrier;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class CyclicBarrierCountExampleUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenCyclicBarrier_notCompleted() {
|
||||
CyclicBarrierCountExample ex = new CyclicBarrierCountExample(2);
|
||||
boolean isCompleted = ex.callTwiceInSameThread();
|
||||
assertFalse(isCompleted);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
package com.baeldung.concurrent.cyclicbarrier;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class CyclicBarrierResetExampleUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenCyclicBarrier_reset() {
|
||||
CyclicBarrierResetExample ex = new CyclicBarrierResetExample(7,20);
|
||||
int lineCount = ex.countWaits();
|
||||
assertTrue(lineCount > 7);
|
||||
}
|
||||
}
|
|
@ -34,3 +34,4 @@
|
|||
- [Read a File into an ArrayList](https://www.baeldung.com/java-file-to-arraylist)
|
||||
- [Guide to Java OutputStream](https://www.baeldung.com/java-outputstream)
|
||||
- [Reading a CSV File into an Array](https://www.baeldung.com/java-csv-file-array)
|
||||
- [Guide to BufferedReader](https://www.baeldung.com/java-buffered-reader)
|
||||
|
|
|
@ -56,4 +56,6 @@
|
|||
- [How to Separate Double into Integer and Decimal Parts](https://www.baeldung.com/java-separate-double-into-integer-decimal-parts)
|
||||
- [“Sneaky Throws” in Java](http://www.baeldung.com/java-sneaky-throws)
|
||||
- [Inheritance and Composition (Is-a vs Has-a relationship) in Java](http://www.baeldung.com/java-inheritance-composition)
|
||||
- [A Guide to Constructors in Java](https://www.baeldung.com/java-constructors)
|
||||
- [Retrieving a Class Name in Java](https://www.baeldung.com/java-class-name)
|
||||
|
||||
|
|
|
@ -66,6 +66,12 @@
|
|||
<artifactId>mail</artifactId>
|
||||
<version>${javax.mail.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>nl.jqno.equalsverifier</groupId>
|
||||
<artifactId>equalsverifier</artifactId>
|
||||
<version>${equalsverifier.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
@ -424,6 +430,7 @@
|
|||
<maven-shade-plugin.version>3.1.1</maven-shade-plugin.version>
|
||||
<spring-boot-maven-plugin.version>2.0.3.RELEASE</spring-boot-maven-plugin.version>
|
||||
<exec-maven-plugin.version>1.6.0</exec-maven-plugin.version>
|
||||
<equalsverifier.version>3.0.3</equalsverifier.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -0,0 +1,9 @@
|
|||
package com.baeldung.className;
|
||||
|
||||
public class RetrievingClassName {
|
||||
|
||||
public class InnerClass {
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,56 @@
|
|||
package com.baeldung.constructors;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
class BankAccount {
|
||||
String name;
|
||||
LocalDateTime opened;
|
||||
double balance;
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format("%s, %s, %f", this.name, this.opened.toString(), this.balance);
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public LocalDateTime getOpened() {
|
||||
return opened;
|
||||
}
|
||||
|
||||
public double getBalance() {
|
||||
return this.balance;
|
||||
}
|
||||
}
|
||||
|
||||
class BankAccountEmptyConstructor extends BankAccount {
|
||||
public BankAccountEmptyConstructor() {
|
||||
this.name = "";
|
||||
this.opened = LocalDateTime.now();
|
||||
this.balance = 0.0d;
|
||||
}
|
||||
}
|
||||
|
||||
class BankAccountParameterizedConstructor extends BankAccount {
|
||||
public BankAccountParameterizedConstructor(String name, LocalDateTime opened, double balance) {
|
||||
this.name = name;
|
||||
this.opened = opened;
|
||||
this.balance = balance;
|
||||
}
|
||||
}
|
||||
|
||||
class BankAccountCopyConstructor extends BankAccount {
|
||||
public BankAccountCopyConstructor(String name, LocalDateTime opened, double balance) {
|
||||
this.name = name;
|
||||
this.opened = opened;
|
||||
this.balance = balance;
|
||||
}
|
||||
|
||||
public BankAccountCopyConstructor(BankAccount other) {
|
||||
this.name = other.name;
|
||||
this.opened = LocalDateTime.now();
|
||||
this.balance = 0.0f;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
package com.baeldung.constructors;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
class Transaction {
|
||||
final BankAccountEmptyConstructor bankAccount;
|
||||
final LocalDateTime date;
|
||||
final double amount;
|
||||
|
||||
public Transaction(BankAccountEmptyConstructor account, LocalDateTime date, double amount) {
|
||||
this.bankAccount = account;
|
||||
this.date = date;
|
||||
this.amount = amount;
|
||||
}
|
||||
|
||||
/*
|
||||
* Compilation Error :'(, all final variables must be explicitly initialised.
|
||||
* public Transaction() {
|
||||
* }
|
||||
*/
|
||||
|
||||
public void invalidMethod() {
|
||||
// this.amount = 102.03; // Results in a compiler error. You cannot change the value of a final variable.
|
||||
}
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package com.baeldung.equalshashcode;
|
||||
|
||||
class Money {
|
||||
|
||||
int amount;
|
||||
String currencyCode;
|
||||
|
||||
Money(int amount, String currencyCode) {
|
||||
this.amount = amount;
|
||||
this.currencyCode = currencyCode;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (o == this)
|
||||
return true;
|
||||
if (!(o instanceof Money))
|
||||
return false;
|
||||
Money other = (Money)o;
|
||||
boolean currencyCodeEquals = (this.currencyCode == null && other.currencyCode == null)
|
||||
|| (this.currencyCode != null && this.currencyCode.equals(other.currencyCode));
|
||||
return this.amount == other.amount
|
||||
&& currencyCodeEquals;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = 17;
|
||||
result = 31 * result + amount;
|
||||
if (currencyCode != null) {
|
||||
result = 31 * result + currencyCode.hashCode();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
package com.baeldung.equalshashcode;
|
||||
|
||||
class Team {
|
||||
|
||||
final String city;
|
||||
final String department;
|
||||
|
||||
Team(String city, String department) {
|
||||
this.city = city;
|
||||
this.department = department;
|
||||
}
|
||||
|
||||
@Override
|
||||
public final boolean equals(Object o) {
|
||||
if (o == this)
|
||||
return true;
|
||||
if (!(o instanceof Team))
|
||||
return false;
|
||||
Team otherTeam = (Team)o;
|
||||
boolean cityEquals = (this.city == null && otherTeam.city == null)
|
||||
|| this.city != null && this.city.equals(otherTeam.city);
|
||||
boolean departmentEquals = (this.department == null && otherTeam.department == null)
|
||||
|| this.department != null && this.department.equals(otherTeam.department);
|
||||
return cityEquals && departmentEquals;
|
||||
}
|
||||
|
||||
@Override
|
||||
public final int hashCode() {
|
||||
int result = 17;
|
||||
if (city != null) {
|
||||
result = 31 * result + city.hashCode();
|
||||
}
|
||||
if (department != null) {
|
||||
result = 31 * result + department.hashCode();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,38 @@
|
|||
package com.baeldung.equalshashcode;
|
||||
|
||||
class Voucher {
|
||||
|
||||
private Money value;
|
||||
private String store;
|
||||
|
||||
Voucher(int amount, String currencyCode, String store) {
|
||||
this.value = new Money(amount, currencyCode);
|
||||
this.store = store;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (o == this)
|
||||
return true;
|
||||
if (!(o instanceof Voucher))
|
||||
return false;
|
||||
Voucher other = (Voucher)o;
|
||||
boolean valueEquals = (this.value == null && other.value == null)
|
||||
|| (this.value != null && this.value.equals(other.value));
|
||||
boolean storeEquals = (this.store == null && other.store == null)
|
||||
|| (this.store != null && this.store.equals(other.store));
|
||||
return valueEquals && storeEquals;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = 17;
|
||||
if (this.value != null) {
|
||||
result = 31 * result + value.hashCode();
|
||||
}
|
||||
if (this.store != null) {
|
||||
result = 31 * result + store.hashCode();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
package com.baeldung.equalshashcode;
|
||||
|
||||
/* (non-Javadoc)
|
||||
* This class overrides equals, but it doesn't override hashCode.
|
||||
*
|
||||
* To see which problems this leads to:
|
||||
* TeamUnitTest.givenMapKeyWithoutHashCode_whenSearched_thenReturnsWrongValue
|
||||
*/
|
||||
class WrongTeam {
|
||||
|
||||
String city;
|
||||
String department;
|
||||
|
||||
WrongTeam(String city, String department) {
|
||||
this.city = city;
|
||||
this.department = department;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (o == this)
|
||||
return true;
|
||||
if (!(o instanceof WrongTeam))
|
||||
return false;
|
||||
WrongTeam otherTeam = (WrongTeam)o;
|
||||
return this.city == otherTeam.city
|
||||
&& this.department == otherTeam.department;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,47 @@
|
|||
package com.baeldung.equalshashcode;
|
||||
|
||||
/* (non-Javadoc)
|
||||
* This class extends the Money class that has overridden the equals method and once again overrides the equals method.
|
||||
*
|
||||
* To see which problems this leads to:
|
||||
* MoneyUnitTest.givenMoneyAndVoucherInstances_whenEquals_thenReturnValuesArentSymmetric
|
||||
*/
|
||||
class WrongVoucher extends Money {
|
||||
|
||||
private String store;
|
||||
|
||||
WrongVoucher(int amount, String currencyCode, String store) {
|
||||
super(amount, currencyCode);
|
||||
|
||||
this.store = store;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (o == this)
|
||||
return true;
|
||||
if (!(o instanceof WrongVoucher))
|
||||
return false;
|
||||
WrongVoucher other = (WrongVoucher)o;
|
||||
boolean currencyCodeEquals = (this.currencyCode == null && other.currencyCode == null)
|
||||
|| (this.currencyCode != null && this.currencyCode.equals(other.currencyCode));
|
||||
boolean storeEquals = (this.store == null && other.store == null)
|
||||
|| (this.store != null && this.store.equals(other.store));
|
||||
return this.amount == other.amount
|
||||
&& currencyCodeEquals
|
||||
&& storeEquals;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = 17;
|
||||
result = 31 * result + amount;
|
||||
if (this.currencyCode != null) {
|
||||
result = 31 * result + currencyCode.hashCode();
|
||||
}
|
||||
if (this.store != null) {
|
||||
result = 31 * result + store.hashCode();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,156 @@
|
|||
package com.baeldung.className;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNull;
|
||||
|
||||
public class RetrievingClassNameUnitTest {
|
||||
|
||||
// Retrieving Simple Name
|
||||
@Test
|
||||
public void givenRetrievingClassName_whenGetSimpleName_thenRetrievingClassName() {
|
||||
assertEquals("RetrievingClassName", RetrievingClassName.class.getSimpleName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPrimitiveInt_whenGetSimpleName_thenInt() {
|
||||
assertEquals("int", int.class.getSimpleName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRetrievingClassNameArray_whenGetSimpleName_thenRetrievingClassNameWithBrackets() {
|
||||
assertEquals("RetrievingClassName[]", RetrievingClassName[].class.getSimpleName());
|
||||
assertEquals("RetrievingClassName[][]", RetrievingClassName[][].class.getSimpleName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnonymousClass_whenGetSimpleName_thenEmptyString() {
|
||||
assertEquals("", new RetrievingClassName() {}.getClass().getSimpleName());
|
||||
}
|
||||
|
||||
// Retrieving Other Names
|
||||
// - Primitive Types
|
||||
@Test
|
||||
public void givenPrimitiveInt_whenGetName_thenInt() {
|
||||
assertEquals("int", int.class.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPrimitiveInt_whenGetTypeName_thenInt() {
|
||||
assertEquals("int", int.class.getTypeName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPrimitiveInt_whenGetCanonicalName_thenInt() {
|
||||
assertEquals("int", int.class.getCanonicalName());
|
||||
}
|
||||
|
||||
// - Object Types
|
||||
@Test
|
||||
public void givenRetrievingClassName_whenGetName_thenCanonicalName() {
|
||||
assertEquals("com.baeldung.className.RetrievingClassName", RetrievingClassName.class.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRetrievingClassName_whenGetTypeName_thenCanonicalName() {
|
||||
assertEquals("com.baeldung.className.RetrievingClassName", RetrievingClassName.class.getTypeName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRetrievingClassName_whenGetCanonicalName_thenCanonicalName() {
|
||||
assertEquals("com.baeldung.className.RetrievingClassName", RetrievingClassName.class.getCanonicalName());
|
||||
}
|
||||
|
||||
// - Inner Classes
|
||||
@Test
|
||||
public void givenRetrievingClassNameInnerClass_whenGetName_thenCanonicalNameWithDollarSeparator() {
|
||||
assertEquals("com.baeldung.className.RetrievingClassName$InnerClass", RetrievingClassName.InnerClass.class.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRetrievingClassNameInnerClass_whenGetTypeName_thenCanonicalNameWithDollarSeparator() {
|
||||
assertEquals("com.baeldung.className.RetrievingClassName$InnerClass", RetrievingClassName.InnerClass.class.getTypeName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRetrievingClassNameInnerClass_whenGetCanonicalName_thenCanonicalName() {
|
||||
assertEquals("com.baeldung.className.RetrievingClassName.InnerClass", RetrievingClassName.InnerClass.class.getCanonicalName());
|
||||
}
|
||||
|
||||
// - Anonymous Classes
|
||||
@Test
|
||||
public void givenAnonymousClass_whenGetName_thenCallingClassCanonicalNameWithDollarSeparatorAndCountNumber() {
|
||||
// These are the second and third appearences of an anonymous class in RetrievingClassNameUnitTest, hence $2 and $3 expectations
|
||||
assertEquals("com.baeldung.className.RetrievingClassNameUnitTest$2", new RetrievingClassName() {}.getClass().getName());
|
||||
assertEquals("com.baeldung.className.RetrievingClassNameUnitTest$3", new RetrievingClassName() {}.getClass().getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnonymousClass_whenGetTypeName_thenCallingClassCanonicalNameWithDollarSeparatorAndCountNumber() {
|
||||
// These are the fourth and fifth appearences of an anonymous class in RetrievingClassNameUnitTest, hence $4 and $5 expectations
|
||||
assertEquals("com.baeldung.className.RetrievingClassNameUnitTest$4", new RetrievingClassName() {}.getClass().getTypeName());
|
||||
assertEquals("com.baeldung.className.RetrievingClassNameUnitTest$5", new RetrievingClassName() {}.getClass().getTypeName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnonymousClass_whenGetCanonicalName_thenNull() {
|
||||
assertNull(new RetrievingClassName() {}.getClass().getCanonicalName());
|
||||
}
|
||||
|
||||
// - Arrays
|
||||
@Test
|
||||
public void givenPrimitiveIntArray_whenGetName_thenOpeningBracketsAndPrimitiveIntLetter() {
|
||||
assertEquals("[I", int[].class.getName());
|
||||
assertEquals("[[I", int[][].class.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRetrievingClassNameArray_whenGetName_thenOpeningBracketsLetterLAndRetrievingClassNameGetName() {
|
||||
assertEquals("[Lcom.baeldung.className.RetrievingClassName;", RetrievingClassName[].class.getName());
|
||||
assertEquals("[[Lcom.baeldung.className.RetrievingClassName;", RetrievingClassName[][].class.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRetrievingClassNameInnerClassArray_whenGetName_thenOpeningBracketsLetterLAndRetrievingClassNameInnerClassGetName() {
|
||||
assertEquals("[Lcom.baeldung.className.RetrievingClassName$InnerClass;", RetrievingClassName.InnerClass[].class.getName());
|
||||
assertEquals("[[Lcom.baeldung.className.RetrievingClassName$InnerClass;", RetrievingClassName.InnerClass[][].class.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPrimitiveIntArray_whenGetTypeName_thenPrimitiveIntGetTypeNameWithBrackets() {
|
||||
assertEquals("int[]", int[].class.getTypeName());
|
||||
assertEquals("int[][]", int[][].class.getTypeName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRetrievingClassNameArray_whenGetTypeName_thenRetrievingClassNameGetTypeNameWithBrackets() {
|
||||
assertEquals("com.baeldung.className.RetrievingClassName[]", RetrievingClassName[].class.getTypeName());
|
||||
assertEquals("com.baeldung.className.RetrievingClassName[][]", RetrievingClassName[][].class.getTypeName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRetrievingClassNameInnerClassArray_whenGetTypeName_thenRetrievingClassNameInnerClassGetTypeNameWithBrackets() {
|
||||
assertEquals("com.baeldung.className.RetrievingClassName$InnerClass[]", RetrievingClassName.InnerClass[].class.getTypeName());
|
||||
assertEquals("com.baeldung.className.RetrievingClassName$InnerClass[][]", RetrievingClassName.InnerClass[][].class.getTypeName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPrimitiveIntArray_whenGetCanonicalName_thenPrimitiveIntGetCanonicalNameWithBrackets() {
|
||||
assertEquals("int[]", int[].class.getCanonicalName());
|
||||
assertEquals("int[][]", int[][].class.getCanonicalName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRetrievingClassNameArray_whenGetCanonicalName_thenRetrievingClassNameGetCanonicalNameWithBrackets() {
|
||||
assertEquals("com.baeldung.className.RetrievingClassName[]", RetrievingClassName[].class.getCanonicalName());
|
||||
assertEquals("com.baeldung.className.RetrievingClassName[][]", RetrievingClassName[][].class.getCanonicalName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRetrievingClassNameInnerClassArray_whenGetCanonicalName_thenRetrievingClassNameInnerClassGetCanonicalNameWithBrackets() {
|
||||
assertEquals("com.baeldung.className.RetrievingClassName.InnerClass[]", RetrievingClassName.InnerClass[].class.getCanonicalName());
|
||||
assertEquals("com.baeldung.className.RetrievingClassName.InnerClass[][]", RetrievingClassName.InnerClass[][].class.getCanonicalName());
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,111 @@
|
|||
package com.baeldung.compoundoperators;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class CompoundOperatorsUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenAssignmentOperatorIsUsed_thenValueIsAssigned() {
|
||||
int x = 5;
|
||||
|
||||
assertEquals(5, x);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCompoundAssignmentUsed_thenSameAsSimpleAssignment() {
|
||||
int a = 3, b = 3, c = -2;
|
||||
a = a * c; // Simple assignment operator
|
||||
b *= c; // Compound assignment operator
|
||||
|
||||
assertEquals(a, b);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAssignmentOperatorIsUsed_thenValueIsReturned() {
|
||||
long x = 1;
|
||||
long y = (x+=2);
|
||||
|
||||
assertEquals(3, y);
|
||||
assertEquals(y, x);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCompoundOperatorsAreUsed_thenOperationsArePerformedAndAssigned() {
|
||||
//Simple assignment
|
||||
int x = 5; //x is 5
|
||||
|
||||
//Incrementation
|
||||
x += 5; //x is 10
|
||||
assertEquals(10, x);
|
||||
|
||||
//Decrementation
|
||||
x -= 2; //x is 8
|
||||
assertEquals(8, x);
|
||||
|
||||
//Multiplication
|
||||
x *= 2; //x is 16
|
||||
assertEquals(16, x);
|
||||
|
||||
//Division
|
||||
x /= 4; //x is 4
|
||||
assertEquals(4, x);
|
||||
|
||||
//Modulus
|
||||
x %= 3; //x is 1
|
||||
assertEquals(1, x);
|
||||
|
||||
|
||||
//Binary AND
|
||||
x &= 4; //x is 0
|
||||
assertEquals(0, x);
|
||||
|
||||
//Binary exclusive OR
|
||||
x ^= 4; //x is 4
|
||||
assertEquals(4, x);
|
||||
|
||||
//Binary inclusive OR
|
||||
x |= 8; //x is 12
|
||||
assertEquals(12, x);
|
||||
|
||||
|
||||
//Binary Left Shift
|
||||
x <<= 2; //x is 48
|
||||
assertEquals(48, x);
|
||||
|
||||
//Binary Right Shift
|
||||
x >>= 2; //x is 12
|
||||
assertEquals(12, x);
|
||||
|
||||
//Shift right zero fill
|
||||
x >>>= 1; //x is 6
|
||||
assertEquals(6, x);
|
||||
}
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void whenArrayIsNull_thenThrowNullException() {
|
||||
int[] numbers = null;
|
||||
|
||||
//Trying Incrementation
|
||||
numbers[2] += 5;
|
||||
}
|
||||
|
||||
@Test(expected = ArrayIndexOutOfBoundsException.class)
|
||||
public void whenArrayIndexNotCorrect_thenThrowArrayIndexException() {
|
||||
int[] numbers = {0, 1};
|
||||
|
||||
//Trying Incrementation
|
||||
numbers[2] += 5;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenArrayIndexIsCorrect_thenPerformOperation() {
|
||||
int[] numbers = {0, 1};
|
||||
|
||||
//Incrementation
|
||||
numbers[1] += 5;
|
||||
assertEquals(6, numbers[1]);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,53 @@
|
|||
package com.baeldung.constructors;
|
||||
|
||||
import com.baeldung.constructors.*;
|
||||
|
||||
import java.util.logging.Logger;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.Month;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
public class ConstructorUnitTest {
|
||||
final static Logger LOGGER = Logger.getLogger(ConstructorUnitTest.class.getName());
|
||||
|
||||
@Test
|
||||
public void givenNoExplicitContructor_whenUsed_thenFails() {
|
||||
BankAccount account = new BankAccount();
|
||||
assertThatThrownBy(() -> { account.toString(); }).isInstanceOf(Exception.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNoArgumentConstructor_whenUsed_thenSucceeds() {
|
||||
BankAccountEmptyConstructor account = new BankAccountEmptyConstructor();
|
||||
assertThatCode(() -> {
|
||||
account.toString();
|
||||
}).doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenParameterisedConstructor_whenUsed_thenSucceeds() {
|
||||
LocalDateTime opened = LocalDateTime.of(2018, Month.JUNE, 29, 06, 30, 00);
|
||||
BankAccountParameterizedConstructor account =
|
||||
new BankAccountParameterizedConstructor("Tom", opened, 1000.0f);
|
||||
|
||||
assertThatCode(() -> {
|
||||
account.toString();
|
||||
}).doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCopyContructor_whenUser_thenMaintainsLogic() {
|
||||
LocalDateTime opened = LocalDateTime.of(2018, Month.JUNE, 29, 06, 30, 00);
|
||||
BankAccountCopyConstructor account = new BankAccountCopyConstructor("Tim", opened, 1000.0f);
|
||||
BankAccountCopyConstructor newAccount = new BankAccountCopyConstructor(account);
|
||||
|
||||
assertThat(account.getName()).isEqualTo(newAccount.getName());
|
||||
assertThat(account.getOpened()).isNotEqualTo(newAccount.getOpened());
|
||||
|
||||
assertThat(newAccount.getBalance()).isEqualTo(0.0f);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
package com.baeldung.equalshashcode;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class MoneyUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenMoneyInstancesWithSameAmountAndCurrency_whenEquals_thenReturnsTrue() {
|
||||
Money income = new Money(55, "USD");
|
||||
Money expenses = new Money(55, "USD");
|
||||
|
||||
assertTrue(income.equals(expenses));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMoneyAndVoucherInstances_whenEquals_thenReturnValuesArentSymmetric() {
|
||||
Money cash = new Money(42, "USD");
|
||||
WrongVoucher voucher = new WrongVoucher(42, "USD", "Amazon");
|
||||
|
||||
assertFalse(voucher.equals(cash));
|
||||
assertTrue(cash.equals(voucher));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,46 @@
|
|||
package com.baeldung.equalshashcode;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import nl.jqno.equalsverifier.EqualsVerifier;
|
||||
|
||||
public class TeamUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenMapKeyWithHashCode_whenSearched_thenReturnsCorrectValue() {
|
||||
Map<Team,String> leaders = new HashMap<>();
|
||||
leaders.put(new Team("New York", "development"), "Anne");
|
||||
leaders.put(new Team("Boston", "development"), "Brian");
|
||||
leaders.put(new Team("Boston", "marketing"), "Charlie");
|
||||
|
||||
Team myTeam = new Team("New York", "development");
|
||||
String myTeamleader = leaders.get(myTeam);
|
||||
|
||||
assertEquals("Anne", myTeamleader);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMapKeyWithoutHashCode_whenSearched_thenReturnsWrongValue() {
|
||||
Map<WrongTeam,String> leaders = new HashMap<>();
|
||||
leaders.put(new WrongTeam("New York", "development"), "Anne");
|
||||
leaders.put(new WrongTeam("Boston", "development"), "Brian");
|
||||
leaders.put(new WrongTeam("Boston", "marketing"), "Charlie");
|
||||
|
||||
WrongTeam myTeam = new WrongTeam("New York", "development");
|
||||
String myTeamleader = leaders.get(myTeam);
|
||||
|
||||
assertFalse("Anne".equals(myTeamleader));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void equalsContract() {
|
||||
EqualsVerifier.forClass(Team.class).verify();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
*.class
|
||||
|
||||
0.*
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
.resourceCache
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
|
||||
# Files generated by integration tests
|
||||
backup-pom.xml
|
||||
/bin/
|
||||
/temp
|
||||
|
||||
#IntelliJ specific
|
||||
.idea/
|
||||
*.iml
|
|
@ -0,0 +1,3 @@
|
|||
=========
|
||||
|
||||
## Core Java Net
|
|
@ -0,0 +1,19 @@
|
|||
<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-net</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>core-java-net</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-net</finalName>
|
||||
</build>
|
||||
</project>
|
|
@ -0,0 +1,13 @@
|
|||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
|
@ -85,3 +85,7 @@
|
|||
- [A Guide to SimpleDateFormat](https://www.baeldung.com/java-simple-date-format)
|
||||
- [SSL Handshake Failures](https://www.baeldung.com/java-ssl-handshake-failures)
|
||||
- [Implementing a Binary Tree in Java](https://www.baeldung.com/java-binary-tree)
|
||||
- [Changing the Order in a Sum Operation Can Produce Different Results?](https://www.baeldung.com/java-floating-point-sum-order)
|
||||
- [Java – Try with Resources](https://www.baeldung.com/java-try-with-resources)
|
||||
- [Abstract Classes in Java](https://www.baeldung.com/java-abstract-class)
|
||||
- [Guide to Character Encoding](https://www.baeldung.com/java-char-encoding)
|
||||
|
|
|
@ -3,8 +3,8 @@
|
|||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>core-java</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
|
|
|
@ -0,0 +1,76 @@
|
|||
package com.baeldung.graph;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class Graph {
|
||||
private Map<Vertex, List<Vertex>> adjVertices;
|
||||
|
||||
Graph() {
|
||||
this.adjVertices = new HashMap<Vertex, List<Vertex>>();
|
||||
}
|
||||
|
||||
void addVertex(String label) {
|
||||
adjVertices.putIfAbsent(new Vertex(label), new ArrayList<>());
|
||||
}
|
||||
|
||||
void removeVertex(String label) {
|
||||
Vertex v = new Vertex(label);
|
||||
adjVertices.values().stream().map(e -> e.remove(v)).collect(Collectors.toList());
|
||||
adjVertices.remove(new Vertex(label));
|
||||
}
|
||||
|
||||
void addEdge(String label1, String label2) {
|
||||
Vertex v1 = new Vertex(label1);
|
||||
Vertex v2 = new Vertex(label2);
|
||||
adjVertices.get(v1).add(v2);
|
||||
adjVertices.get(v2).add(v1);
|
||||
}
|
||||
|
||||
void removeEdge(String label1, String label2) {
|
||||
Vertex v1 = new Vertex(label1);
|
||||
Vertex v2 = new Vertex(label2);
|
||||
List<Vertex> eV1 = adjVertices.get(v1);
|
||||
List<Vertex> eV2 = adjVertices.get(v2);
|
||||
if (eV1 != null)
|
||||
eV1.remove(v2);
|
||||
if (eV2 != null)
|
||||
eV2.remove(v1);
|
||||
}
|
||||
|
||||
List<Vertex> getAdjVertices(String label) {
|
||||
return adjVertices.get(new Vertex(label));
|
||||
}
|
||||
|
||||
String printGraph() {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
for(Vertex v : adjVertices.keySet()) {
|
||||
sb.append(v);
|
||||
sb.append(adjVertices.get(v));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
class Vertex {
|
||||
String label;
|
||||
Vertex(String label) {
|
||||
this.label = label;
|
||||
}
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
Vertex vertex = (Vertex) obj;
|
||||
return vertex.label == label;
|
||||
}
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return label.hashCode();
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return label;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,44 @@
|
|||
package com.baeldung.graph;
|
||||
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.LinkedList;
|
||||
import java.util.Queue;
|
||||
import java.util.Set;
|
||||
import java.util.Stack;
|
||||
|
||||
import com.baeldung.graph.Graph.Vertex;
|
||||
|
||||
public class GraphTraversal {
|
||||
static Set<String> depthFirstTraversal(Graph graph, String root) {
|
||||
Set<String> visited = new LinkedHashSet<String>();
|
||||
Stack<String> stack = new Stack<String>();
|
||||
stack.push(root);
|
||||
while (!stack.isEmpty()) {
|
||||
String vertex = stack.pop();
|
||||
if (!visited.contains(vertex)) {
|
||||
visited.add(vertex);
|
||||
for (Vertex v : graph.getAdjVertices(vertex)) {
|
||||
stack.push(v.label);
|
||||
}
|
||||
}
|
||||
}
|
||||
return visited;
|
||||
}
|
||||
|
||||
static Set<String> breadthFirstTraversal(Graph graph, String root) {
|
||||
Set<String> visited = new LinkedHashSet<String>();
|
||||
Queue<String> queue = new LinkedList<String>();
|
||||
queue.add(root);
|
||||
visited.add(root);
|
||||
while (!queue.isEmpty()) {
|
||||
String vertex = queue.poll();
|
||||
for (Vertex v : graph.getAdjVertices(vertex)) {
|
||||
if (!visited.contains(v.label)) {
|
||||
visited.add(v.label);
|
||||
queue.add(v.label);
|
||||
}
|
||||
}
|
||||
}
|
||||
return visited;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,61 @@
|
|||
package com.baeldung.printf;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.Locale;
|
||||
|
||||
public class PrintfExamples {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
printfNewLine();
|
||||
printfChar();
|
||||
printfString();
|
||||
printfNumber();
|
||||
printfDateTime();
|
||||
printfBoolean();
|
||||
}
|
||||
|
||||
private static void printfNewLine() {
|
||||
System.out.printf("baeldung%nline%nterminator");
|
||||
}
|
||||
|
||||
private static void printfString() {
|
||||
System.out.printf("'%s' %n", "baeldung");
|
||||
System.out.printf("'%S' %n", "baeldung");
|
||||
System.out.printf("'%15s' %n", "baeldung");
|
||||
System.out.printf("'%-10s' %n", "baeldung");
|
||||
}
|
||||
|
||||
private static void printfChar() {
|
||||
System.out.printf("%c%n", 's');
|
||||
System.out.printf("%C%n", 's');
|
||||
}
|
||||
|
||||
private static void printfNumber() {
|
||||
System.out.printf("simple integer: %d%n", 10000L);
|
||||
|
||||
System.out.printf(Locale.US, "%,d %n", 10000);
|
||||
System.out.printf(Locale.ITALY, "%,d %n", 10000);
|
||||
|
||||
System.out.printf("%f%n", 5.1473);
|
||||
System.out.printf("'%5.2f'%n", 5.1473);
|
||||
System.out.printf("'%5.2e'%n", 5.1473);
|
||||
}
|
||||
|
||||
private static void printfBoolean() {
|
||||
System.out.printf("%b%n", null);
|
||||
System.out.printf("%B%n", false);
|
||||
System.out.printf("%B%n", 5.3);
|
||||
System.out.printf("%b%n", "random text");
|
||||
}
|
||||
|
||||
private static void printfDateTime() {
|
||||
Date date = new Date();
|
||||
System.out.printf("%tT%n", date);
|
||||
System.out.printf("hours %tH: minutes %tM: seconds %tS%n", date, date, date);
|
||||
System.out.printf("%1$tH:%1$tM:%1$tS %1$tp %1$tL %1$tN %1$tz %n", date);
|
||||
|
||||
System.out.printf("%1$tA %1$tB %1$tY %n", date);
|
||||
System.out.printf("%1$td.%1$tm.%1$ty %n", date);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package com.baeldung.graph;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class GraphTraversalUnitTest {
|
||||
@Test
|
||||
public void givenAGraph_whenTraversingDepthFirst_thenExpectedResult() {
|
||||
Graph graph = createGraph();
|
||||
Assert.assertEquals("[Bob, Rob, Maria, Alice, Mark]",
|
||||
GraphTraversal.depthFirstTraversal(graph, "Bob").toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAGraph_whenTraversingBreadthFirst_thenExpectedResult() {
|
||||
Graph graph = createGraph();
|
||||
Assert.assertEquals("[Bob, Alice, Rob, Mark, Maria]",
|
||||
GraphTraversal.breadthFirstTraversal(graph, "Bob").toString());
|
||||
}
|
||||
|
||||
Graph createGraph() {
|
||||
Graph graph = new Graph();
|
||||
graph.addVertex("Bob");
|
||||
graph.addVertex("Alice");
|
||||
graph.addVertex("Mark");
|
||||
graph.addVertex("Rob");
|
||||
graph.addVertex("Maria");
|
||||
graph.addEdge("Bob", "Alice");
|
||||
graph.addEdge("Bob", "Rob");
|
||||
graph.addEdge("Alice", "Mark");
|
||||
graph.addEdge("Rob", "Mark");
|
||||
graph.addEdge("Alice", "Maria");
|
||||
graph.addEdge("Rob", "Maria");
|
||||
return graph;
|
||||
}
|
||||
}
|
|
@ -11,7 +11,7 @@ import java.util.regex.Pattern;
|
|||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class OptimizedMatcherUnitTest {
|
||||
public class OptimizedMatcherManualTest {
|
||||
|
||||
private String action;
|
||||
|
|
@ -0,0 +1,83 @@
|
|||
package com.baeldung.string;
|
||||
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class StringReplaceAndRemoveUnitTest {
|
||||
|
||||
|
||||
@Test
|
||||
public void givenTestStrings_whenReplace_thenProcessedString() {
|
||||
|
||||
String master = "Hello World Baeldung!";
|
||||
String target = "Baeldung";
|
||||
String replacement = "Java";
|
||||
String processed = master.replace(target, replacement);
|
||||
assertTrue(processed.contains(replacement));
|
||||
assertFalse(processed.contains(target));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTestStrings_whenReplaceAll_thenProcessedString() {
|
||||
|
||||
String master2 = "Welcome to Baeldung, Hello World Baeldung";
|
||||
String regexTarget= "(Baeldung)$";
|
||||
String replacement = "Java";
|
||||
String processed2 = master2.replaceAll(regexTarget, replacement);
|
||||
assertTrue(processed2.endsWith("Java"));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTestStrings_whenStringBuilderMethods_thenProcessedString() {
|
||||
|
||||
String master = "Hello World Baeldung!";
|
||||
String target = "Baeldung";
|
||||
String replacement = "Java";
|
||||
|
||||
int startIndex = master.indexOf(target);
|
||||
int stopIndex = startIndex + target.length();
|
||||
|
||||
StringBuilder builder = new StringBuilder(master);
|
||||
|
||||
|
||||
builder.delete(startIndex, stopIndex);
|
||||
assertFalse(builder.toString().contains(target));
|
||||
|
||||
|
||||
builder.replace(startIndex, stopIndex, replacement);
|
||||
assertTrue(builder.toString().contains(replacement));
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenTestStrings_whenStringUtilsMethods_thenProcessedStrings() {
|
||||
|
||||
String master = "Hello World Baeldung!";
|
||||
String target = "Baeldung";
|
||||
String replacement = "Java";
|
||||
|
||||
String processed = StringUtils.replace(master, target, replacement);
|
||||
assertTrue(processed.contains(replacement));
|
||||
|
||||
String master2 = "Hello World Baeldung!";
|
||||
String target2 = "baeldung";
|
||||
String processed2 = StringUtils.replaceIgnoreCase(master2, target2, replacement);
|
||||
assertFalse(processed2.contains(target));
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue