Merge branch 'master' into BAEL-2775
This commit is contained in:
commit
b7cbac712e
|
@ -19,6 +19,7 @@
|
|||
.idea/
|
||||
*.iml
|
||||
*.iws
|
||||
out/
|
||||
|
||||
# Mac
|
||||
.DS_Store
|
||||
|
@ -27,6 +28,9 @@
|
|||
log/
|
||||
target/
|
||||
|
||||
# Gradle
|
||||
.gradle/
|
||||
|
||||
spring-openid/src/main/resources/application.properties
|
||||
.recommenders/
|
||||
/spring-hibernate4/nbproject/
|
||||
|
|
|
@ -14,18 +14,19 @@
|
|||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.typesafe.akka</groupId>
|
||||
<artifactId>akka-stream_2.11</artifactId>
|
||||
<artifactId>akka-stream_${scala.version}</artifactId>
|
||||
<version>${akkastreams.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.typesafe.akka</groupId>
|
||||
<artifactId>akka-stream-testkit_2.11</artifactId>
|
||||
<artifactId>akka-stream-testkit_${scala.version}</artifactId>
|
||||
<version>${akkastreams.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<akkastreams.version>2.5.2</akkastreams.version>
|
||||
<scala.version>2.11</scala.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -14,7 +14,5 @@
|
|||
- [Calculate Factorial in Java](https://www.baeldung.com/java-calculate-factorial)
|
||||
- [Find Substrings That Are Palindromes in Java](https://www.baeldung.com/java-palindrome-substrings)
|
||||
- [Find the Longest Substring without Repeating Characters](https://www.baeldung.com/java-longest-substring-without-repeated-characters)
|
||||
- [Java Two Pointer Technique](https://www.baeldung.com/java-two-pointer-technique)
|
||||
- [Permutations of an Array in Java](https://www.baeldung.com/java-array-permutations)
|
||||
- [Implementing Simple State Machines with Java Enums](https://www.baeldung.com/java-enum-simple-state-machine)
|
||||
- [Generate Combinations in Java](https://www.baeldung.com/java-combinations-algorithm)
|
||||
|
|
|
@ -8,9 +8,6 @@
|
|||
- [Create a Sudoku Solver in Java](http://www.baeldung.com/java-sudoku)
|
||||
- [Displaying Money Amounts in Words](http://www.baeldung.com/java-money-into-words)
|
||||
- [A Collaborative Filtering Recommendation System in Java](http://www.baeldung.com/java-collaborative-filtering-recommendations)
|
||||
- [Converting Between Roman and Arabic Numerals in Java](http://www.baeldung.com/java-convert-roman-arabic)
|
||||
- [Practical Java Examples of the Big O Notation](http://www.baeldung.com/java-algorithm-complexity)
|
||||
- [An Introduction to the Theory of Big-O Notation](http://www.baeldung.com/big-o-notation)
|
||||
- [Check If Two Rectangles Overlap In Java](https://www.baeldung.com/java-check-if-two-rectangles-overlap)
|
||||
- [Calculate the Distance Between Two Points in Java](https://www.baeldung.com/java-distance-between-two-points)
|
||||
- [Find the Intersection of Two Lines in Java](https://www.baeldung.com/java-intersection-of-two-lines)
|
||||
|
|
|
@ -0,0 +1,45 @@
|
|||
package com.baeldung.algorithms.relativelyprime;
|
||||
|
||||
import java.math.BigInteger;
|
||||
|
||||
class RelativelyPrime {
|
||||
|
||||
static boolean iterativeRelativelyPrime(int a, int b) {
|
||||
return iterativeGCD(a, b) == 1;
|
||||
}
|
||||
|
||||
static boolean recursiveRelativelyPrime(int a, int b) {
|
||||
return recursiveGCD(a, b) == 1;
|
||||
}
|
||||
|
||||
static boolean bigIntegerRelativelyPrime(int a, int b) {
|
||||
return BigInteger.valueOf(a).gcd(BigInteger.valueOf(b)).equals(BigInteger.ONE);
|
||||
}
|
||||
|
||||
private static int iterativeGCD(int a, int b) {
|
||||
int tmp;
|
||||
while (b != 0) {
|
||||
if (a < b) {
|
||||
tmp = a;
|
||||
a = b;
|
||||
b = tmp;
|
||||
}
|
||||
tmp = b;
|
||||
b = a % b;
|
||||
a = tmp;
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
private static int recursiveGCD(int a, int b) {
|
||||
if (b == 0) {
|
||||
return a;
|
||||
}
|
||||
if (a < b) {
|
||||
return recursiveGCD(b, a);
|
||||
}
|
||||
return recursiveGCD(b, a % b);
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -1,42 +1,42 @@
|
|||
package com.baeldung.algorithms.reversingtree;
|
||||
|
||||
public class TreeNode {
|
||||
|
||||
private int value;
|
||||
private TreeNode rightChild;
|
||||
private TreeNode leftChild;
|
||||
|
||||
public int getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public void setValue(int value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public TreeNode getRightChild() {
|
||||
return rightChild;
|
||||
}
|
||||
|
||||
public void setRightChild(TreeNode rightChild) {
|
||||
this.rightChild = rightChild;
|
||||
}
|
||||
|
||||
public TreeNode getLeftChild() {
|
||||
return leftChild;
|
||||
}
|
||||
|
||||
public void setLeftChild(TreeNode leftChild) {
|
||||
this.leftChild = leftChild;
|
||||
}
|
||||
|
||||
public TreeNode(int value, TreeNode rightChild, TreeNode leftChild) {
|
||||
this.value = value;
|
||||
this.rightChild = rightChild;
|
||||
this.leftChild = leftChild;
|
||||
}
|
||||
|
||||
public TreeNode(int value) {
|
||||
this.value = value;
|
||||
}
|
||||
}
|
||||
package com.baeldung.algorithms.reversingtree;
|
||||
|
||||
public class TreeNode {
|
||||
|
||||
private int value;
|
||||
private TreeNode rightChild;
|
||||
private TreeNode leftChild;
|
||||
|
||||
public int getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public void setValue(int value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public TreeNode getRightChild() {
|
||||
return rightChild;
|
||||
}
|
||||
|
||||
public void setRightChild(TreeNode rightChild) {
|
||||
this.rightChild = rightChild;
|
||||
}
|
||||
|
||||
public TreeNode getLeftChild() {
|
||||
return leftChild;
|
||||
}
|
||||
|
||||
public void setLeftChild(TreeNode leftChild) {
|
||||
this.leftChild = leftChild;
|
||||
}
|
||||
|
||||
public TreeNode(int value, TreeNode leftChild, TreeNode rightChild) {
|
||||
this.value = value;
|
||||
this.rightChild = rightChild;
|
||||
this.leftChild = leftChild;
|
||||
}
|
||||
|
||||
public TreeNode(int value) {
|
||||
this.value = value;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,68 +1,53 @@
|
|||
package com.baeldung.algorithms.reversingtree;
|
||||
|
||||
import java.util.LinkedList;
|
||||
|
||||
public class TreeReverser {
|
||||
|
||||
public TreeNode createBinaryTree() {
|
||||
|
||||
TreeNode leaf1 = new TreeNode(3);
|
||||
TreeNode leaf2 = new TreeNode(1);
|
||||
TreeNode leaf3 = new TreeNode(9);
|
||||
TreeNode leaf4 = new TreeNode(6);
|
||||
|
||||
TreeNode nodeLeft = new TreeNode(2, leaf1, leaf2);
|
||||
TreeNode nodeRight = new TreeNode(7, leaf3, leaf4);
|
||||
|
||||
TreeNode root = new TreeNode(4, nodeRight, nodeLeft);
|
||||
|
||||
return root;
|
||||
}
|
||||
|
||||
public void reverseRecursive(TreeNode treeNode) {
|
||||
if (treeNode == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
TreeNode temp = treeNode.getLeftChild();
|
||||
treeNode.setLeftChild(treeNode.getRightChild());
|
||||
treeNode.setRightChild(temp);
|
||||
|
||||
reverseRecursive(treeNode.getLeftChild());
|
||||
reverseRecursive(treeNode.getRightChild());
|
||||
}
|
||||
|
||||
public void reverseIterative(TreeNode treeNode) {
|
||||
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
|
||||
|
||||
if (treeNode != null) {
|
||||
queue.add(treeNode);
|
||||
}
|
||||
|
||||
while (!queue.isEmpty()) {
|
||||
|
||||
TreeNode node = queue.poll();
|
||||
if (node.getLeftChild() != null)
|
||||
queue.add(node.getLeftChild());
|
||||
if (node.getRightChild() != null)
|
||||
queue.add(node.getRightChild());
|
||||
|
||||
TreeNode temp = node.getLeftChild();
|
||||
node.setLeftChild(node.getRightChild());
|
||||
node.setRightChild(temp);
|
||||
}
|
||||
}
|
||||
|
||||
public String toString(TreeNode root) {
|
||||
if (root == null) {
|
||||
return "";
|
||||
}
|
||||
|
||||
StringBuffer buffer = new StringBuffer(String.valueOf(root.getValue())).append(" ");
|
||||
|
||||
buffer.append(toString(root.getLeftChild()));
|
||||
buffer.append(toString(root.getRightChild()));
|
||||
|
||||
return buffer.toString();
|
||||
}
|
||||
}
|
||||
package com.baeldung.algorithms.reversingtree;
|
||||
|
||||
import java.util.LinkedList;
|
||||
|
||||
public class TreeReverser {
|
||||
|
||||
public void reverseRecursive(TreeNode treeNode) {
|
||||
if (treeNode == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
TreeNode temp = treeNode.getLeftChild();
|
||||
treeNode.setLeftChild(treeNode.getRightChild());
|
||||
treeNode.setRightChild(temp);
|
||||
|
||||
reverseRecursive(treeNode.getLeftChild());
|
||||
reverseRecursive(treeNode.getRightChild());
|
||||
}
|
||||
|
||||
public void reverseIterative(TreeNode treeNode) {
|
||||
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
|
||||
|
||||
if (treeNode != null) {
|
||||
queue.add(treeNode);
|
||||
}
|
||||
|
||||
while (!queue.isEmpty()) {
|
||||
|
||||
TreeNode node = queue.poll();
|
||||
if (node.getLeftChild() != null)
|
||||
queue.add(node.getLeftChild());
|
||||
if (node.getRightChild() != null)
|
||||
queue.add(node.getRightChild());
|
||||
|
||||
TreeNode temp = node.getLeftChild();
|
||||
node.setLeftChild(node.getRightChild());
|
||||
node.setRightChild(temp);
|
||||
}
|
||||
}
|
||||
|
||||
public String toString(TreeNode root) {
|
||||
if (root == null) {
|
||||
return "";
|
||||
}
|
||||
|
||||
StringBuffer buffer = new StringBuffer(String.valueOf(root.getValue())).append(" ");
|
||||
|
||||
buffer.append(toString(root.getLeftChild()));
|
||||
buffer.append(toString(root.getRightChild()));
|
||||
|
||||
return buffer.toString();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,51 @@
|
|||
package com.baeldung.algorithms.relativelyprime;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static com.baeldung.algorithms.relativelyprime.RelativelyPrime.*;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class RelativelyPrimeUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenNonRelativelyPrimeNumbers_whenCheckingIteratively_shouldReturnFalse() {
|
||||
|
||||
boolean result = iterativeRelativelyPrime(45, 35);
|
||||
assertThat(result).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRelativelyPrimeNumbers_whenCheckingIteratively_shouldReturnTrue() {
|
||||
|
||||
boolean result = iterativeRelativelyPrime(500, 501);
|
||||
assertThat(result).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNonRelativelyPrimeNumbers_whenCheckingRecursively_shouldReturnFalse() {
|
||||
|
||||
boolean result = recursiveRelativelyPrime(45, 35);
|
||||
assertThat(result).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRelativelyPrimeNumbers_whenCheckingRecursively_shouldReturnTrue() {
|
||||
|
||||
boolean result = recursiveRelativelyPrime(500, 501);
|
||||
assertThat(result).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNonRelativelyPrimeNumbers_whenCheckingUsingBigIntegers_shouldReturnFalse() {
|
||||
|
||||
boolean result = bigIntegerRelativelyPrime(45, 35);
|
||||
assertThat(result).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRelativelyPrimeNumbers_whenCheckingBigIntegers_shouldReturnTrue() {
|
||||
|
||||
boolean result = bigIntegerRelativelyPrime(500, 501);
|
||||
assertThat(result).isTrue();
|
||||
}
|
||||
}
|
|
@ -1,33 +1,47 @@
|
|||
package com.baeldung.algorithms.reversingtree;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class TreeReverserUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenTreeWhenReversingRecursivelyThenReversed() {
|
||||
TreeReverser reverser = new TreeReverser();
|
||||
|
||||
TreeNode treeNode = reverser.createBinaryTree();
|
||||
|
||||
reverser.reverseRecursive(treeNode);
|
||||
|
||||
assertEquals("4 7 9 6 2 3 1", reverser.toString(treeNode)
|
||||
.trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTreeWhenReversingIterativelyThenReversed() {
|
||||
TreeReverser reverser = new TreeReverser();
|
||||
|
||||
TreeNode treeNode = reverser.createBinaryTree();
|
||||
|
||||
reverser.reverseIterative(treeNode);
|
||||
|
||||
assertEquals("4 7 9 6 2 3 1", reverser.toString(treeNode)
|
||||
.trim());
|
||||
}
|
||||
|
||||
}
|
||||
package com.baeldung.algorithms.reversingtree;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class TreeReverserUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenTreeWhenReversingRecursivelyThenReversed() {
|
||||
TreeReverser reverser = new TreeReverser();
|
||||
|
||||
TreeNode treeNode = createBinaryTree();
|
||||
|
||||
reverser.reverseRecursive(treeNode);
|
||||
|
||||
assertEquals("4 7 9 6 2 3 1", reverser.toString(treeNode)
|
||||
.trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTreeWhenReversingIterativelyThenReversed() {
|
||||
TreeReverser reverser = new TreeReverser();
|
||||
|
||||
TreeNode treeNode = createBinaryTree();
|
||||
|
||||
reverser.reverseIterative(treeNode);
|
||||
|
||||
assertEquals("4 7 9 6 2 3 1", reverser.toString(treeNode)
|
||||
.trim());
|
||||
}
|
||||
|
||||
private TreeNode createBinaryTree() {
|
||||
|
||||
TreeNode leaf1 = new TreeNode(1);
|
||||
TreeNode leaf2 = new TreeNode(3);
|
||||
TreeNode leaf3 = new TreeNode(6);
|
||||
TreeNode leaf4 = new TreeNode(9);
|
||||
|
||||
TreeNode nodeRight = new TreeNode(7, leaf3, leaf4);
|
||||
TreeNode nodeLeft = new TreeNode(2, leaf1, leaf2);
|
||||
|
||||
TreeNode root = new TreeNode(4, nodeLeft, nodeRight);
|
||||
|
||||
return root;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,4 @@
|
|||
/target/
|
||||
.settings/
|
||||
.classpath
|
||||
.project
|
|
@ -0,0 +1,7 @@
|
|||
## Relevant articles:
|
||||
|
||||
- [Java Two Pointer Technique](https://www.baeldung.com/java-two-pointer-technique)
|
||||
- [Implementing Simple State Machines with Java Enums](https://www.baeldung.com/java-enum-simple-state-machine)
|
||||
- [Converting Between Roman and Arabic Numerals in Java](http://www.baeldung.com/java-convert-roman-arabic)
|
||||
- [Practical Java Examples of the Big O Notation](http://www.baeldung.com/java-algorithm-complexity)
|
||||
- [An Introduction to the Theory of Big-O Notation](http://www.baeldung.com/big-o-notation)
|
|
@ -0,0 +1,39 @@
|
|||
<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>algorithms-miscellaneous-3</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>algorithms-miscellaneous-3</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${org.assertj.core.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>${exec-maven-plugin.version}</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<org.assertj.core.version>3.9.0</org.assertj.core.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -10,6 +10,14 @@
|
|||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.antlr</groupId>
|
||||
<artifactId>antlr4-runtime</artifactId>
|
||||
<version>${antlr.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
|
@ -44,13 +52,7 @@
|
|||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.antlr</groupId>
|
||||
<artifactId>antlr4-runtime</artifactId>
|
||||
<version>${antlr.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<antlr.version>4.7.1</antlr.version>
|
||||
<mojo.version>3.0.0</mojo.version>
|
||||
|
|
|
@ -12,9 +12,18 @@
|
|||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<cxf-version>3.2.0</cxf-version>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-rs-client</artifactId>
|
||||
<version>${cxf-version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-rs-sse</artifactId>
|
||||
<version>${cxf-version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
|
@ -45,17 +54,8 @@
|
|||
</plugins>
|
||||
</build>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-rs-client</artifactId>
|
||||
<version>${cxf-version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-rs-sse</artifactId>
|
||||
<version>${cxf-version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<properties>
|
||||
<cxf-version>3.2.0</cxf-version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -13,11 +13,28 @@
|
|||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<liberty-maven-plugin.version>2.4.2</liberty-maven-plugin.version>
|
||||
<failOnMissingWebXml>false</failOnMissingWebXml>
|
||||
<openliberty-version>18.0.0.2</openliberty-version>
|
||||
</properties>
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>javax.ws.rs</groupId>
|
||||
<artifactId>javax.ws.rs-api</artifactId>
|
||||
<version>2.1</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.enterprise</groupId>
|
||||
<artifactId>cdi-api</artifactId>
|
||||
<version>2.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.json.bind</groupId>
|
||||
<artifactId>javax.json.bind-api</artifactId>
|
||||
<version>1.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>${project.artifactId}</finalName>
|
||||
|
@ -59,27 +76,10 @@
|
|||
</plugins>
|
||||
</build>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>javax.ws.rs</groupId>
|
||||
<artifactId>javax.ws.rs-api</artifactId>
|
||||
<version>2.1</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.enterprise</groupId>
|
||||
<artifactId>cdi-api</artifactId>
|
||||
<version>2.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.json.bind</groupId>
|
||||
<artifactId>javax.json.bind-api</artifactId>
|
||||
<version>1.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
<properties>
|
||||
<liberty-maven-plugin.version>2.4.2</liberty-maven-plugin.version>
|
||||
<failOnMissingWebXml>false</failOnMissingWebXml>
|
||||
<openliberty-version>18.0.0.2</openliberty-version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -3,7 +3,3 @@
|
|||
## Core Java Cookbooks and Examples
|
||||
|
||||
### Relevant Articles:
|
||||
- [Immutable ArrayList in Java](http://www.baeldung.com/java-immutable-list)
|
||||
- [Java - Reading a Large File Efficiently](http://www.baeldung.com/java-read-lines-large-file)
|
||||
- [Java InputStream to String](http://www.baeldung.com/convert-input-stream-to-string)
|
||||
|
||||
|
|
|
@ -6,6 +6,12 @@
|
|||
<version>0.0.1</version>
|
||||
<name>apache-meecrowave</name>
|
||||
<description>A sample REST API application with Meecrowave</description>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.meecrowave/meecrowave-core -->
|
||||
|
|
|
@ -17,7 +17,7 @@ import okhttp3.Request;
|
|||
import okhttp3.Response;
|
||||
|
||||
@RunWith(MonoMeecrowave.Runner.class)
|
||||
public class ArticleEndpointsTest {
|
||||
public class ArticleEndpointsUnitTest {
|
||||
|
||||
@ConfigurationInject
|
||||
private Meecrowave.Builder config;
|
|
@ -1,8 +1,9 @@
|
|||
package com.baeldung.autofactory.provided;
|
||||
|
||||
import com.baeldung.autofactory.model.Camera;
|
||||
import com.google.auto.factory.AutoFactory;
|
||||
import com.google.auto.factory.Provided;
|
||||
import javafx.scene.Camera;
|
||||
|
||||
|
||||
import javax.inject.Provider;
|
||||
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
### Relevant Articles:
|
||||
|
||||
- [Deploy Spring Boot App to Azure](http://www.baeldung.com/spring-boot-azure)
|
||||
- [Deploy a Spring Boot App to Azure](http://www.baeldung.com/spring-boot-azure)
|
||||
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
### Relevant Articles:
|
||||
|
||||
- [Blade - A Complete GuideBook](http://www.baeldung.com/blade)
|
||||
- [Blade – A Complete Guidebook](http://www.baeldung.com/blade)
|
||||
|
||||
Run Integration Tests with `mvn integration-test`
|
||||
Run Integration Tests with `mvn integration-test`
|
||||
|
|
|
@ -0,0 +1,3 @@
|
|||
### Revelant Articles
|
||||
|
||||
- [A Quick Guide To Using Cloud Foundry UAA](https://www.baeldung.com/cloud-foundry-uaa)
|
|
@ -1,12 +1,7 @@
|
|||
issuer:
|
||||
uri: http://localhost:8080/uaa
|
||||
|
||||
spring_profiles: postgresql,default
|
||||
|
||||
database.driverClassName: org.postgresql.Driver
|
||||
database.url: jdbc:postgresql:uaadb2
|
||||
database.username: postgres
|
||||
database.password: postgres
|
||||
spring_profiles: default,hsqldb
|
||||
|
||||
encryption:
|
||||
active_key_label: CHANGE-THIS-KEY
|
||||
|
|
|
@ -2,24 +2,20 @@
|
|||
<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>
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.1.3.RELEASE</version>
|
||||
<relativePath/> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
<groupId>com.example</groupId>
|
||||
<artifactId>cf-uaa-oauth2-client</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>uaa-client-webapp</name>
|
||||
<description>Demo project for Spring Boot</description>
|
||||
|
||||
<properties>
|
||||
<java.version>1.8</java.version>
|
||||
</properties>
|
||||
<parent>
|
||||
<artifactId>parent-boot-2</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-boot-2</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
|
@ -28,7 +24,6 @@
|
|||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-oauth2-client</artifactId>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
@ -40,4 +35,7 @@
|
|||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<java.version>1.8</java.version>
|
||||
</properties>
|
||||
</project>
|
||||
|
|
|
@ -1,23 +1,11 @@
|
|||
# SECURITY OAUTH2 CLIENT (OAuth2ClientProperties)
|
||||
#spring.security.oauth2.client.provider.*= # OAuth provider details.
|
||||
#spring.security.oauth2.client.registration.*= # OAuth client registrations.
|
||||
|
||||
server.port=8081
|
||||
#server.servlet.context-path=/uaa-client-webapp
|
||||
|
||||
uaa.url=http://localhost:8080/uaa
|
||||
resource.server.url=http://localhost:8082
|
||||
|
||||
spring.security.oauth2.client.registration.uaa.client-name=UAA OAuth2 Client
|
||||
spring.security.oauth2.client.registration.uaa.client-id=client1
|
||||
spring.security.oauth2.client.registration.uaa.client-secret=client1
|
||||
spring.security.oauth2.client.registration.uaa.authorization-grant-type=authorization_code
|
||||
spring.security.oauth2.client.registration.uaa.client-name=Web App Client
|
||||
spring.security.oauth2.client.registration.uaa.client-id=webappclient
|
||||
spring.security.oauth2.client.registration.uaa.client-secret=webappclientsecret
|
||||
spring.security.oauth2.client.registration.uaa.scope=resource.read,resource.write,openid,profile
|
||||
spring.security.oauth2.client.registration.uaa.redirect-uri=http://localhost:8081/login/oauth2/code/uaa
|
||||
#spring.security.oauth2.client.registration.uaa.redirect-uri=http://localhost:8081/**
|
||||
|
||||
spring.security.oauth2.client.provider.uaa.token-uri=${uaa.url}/oauth/token
|
||||
spring.security.oauth2.client.provider.uaa.authorization-uri=${uaa.url}/oauth/authorize
|
||||
spring.security.oauth2.client.provider.uaa.jwk-set-uri=${uaa.url}/token_keys
|
||||
spring.security.oauth2.client.provider.uaa.user-info-uri=${uaa.url}/userinfo
|
||||
spring.security.oauth2.client.provider.uaa.user-name-attribute=user_name
|
||||
spring.security.oauth2.client.provider.uaa.issuer-uri=http://localhost:8080/uaa/oauth/token
|
||||
|
||||
|
|
|
@ -2,24 +2,20 @@
|
|||
<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>
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.1.3.RELEASE</version>
|
||||
<relativePath/> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
<groupId>com.baeldung.cfuaa</groupId>
|
||||
<artifactId>cf-uaa-oauth2-resource-server</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>cf-uaa-oauth2-resource-server</name>
|
||||
<description>Demo project for Spring Boot</description>
|
||||
|
||||
<properties>
|
||||
<java.version>1.8</java.version>
|
||||
</properties>
|
||||
|
||||
<parent>
|
||||
<artifactId>parent-boot-2</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-boot-2</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
|
||||
|
@ -28,7 +24,6 @@
|
|||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
@ -40,4 +35,8 @@
|
|||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<java.version>1.8</java.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -1,16 +1,3 @@
|
|||
server.port=8082
|
||||
|
||||
uaa.url=http://localhost:8080/uaa
|
||||
|
||||
#approch1
|
||||
spring.security.oauth2.resourceserver.jwt.issuer-uri=${uaa.url}/oauth/token
|
||||
|
||||
#approch2
|
||||
#spring.security.oauth2.resourceserver.jwt.jwk-set-uri=${uaa.url}/token_key
|
||||
|
||||
# SECURITY OAUTH2 CLIENT (OAuth2ClientProperties)
|
||||
#security.oauth2.client.client-id=client1
|
||||
#security.oauth2.client.client-secret=client1
|
||||
|
||||
#security.oauth2.resource.jwt.key-uri=${uaa.url}/token_key
|
||||
#security.oauth2.resource.token-info-uri=${uaa.url}/oauth/check_token
|
||||
spring.security.oauth2.resourceserver.jwt.issuer-uri=http://localhost:8080/uaa/oauth/token
|
||||
|
|
|
@ -0,0 +1,7 @@
|
|||
# Groovy
|
||||
|
||||
## Relevant articles:
|
||||
|
||||
- [String Matching in Groovy](http://www.baeldung.com/)
|
||||
- [Groovy def Keyword]
|
||||
|
|
@ -0,0 +1,131 @@
|
|||
<?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-groovy-2</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<name>core-groovy-2</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.groovy</groupId>
|
||||
<artifactId>groovy</artifactId>
|
||||
<version>${groovy.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.groovy</groupId>
|
||||
<artifactId>groovy-all</artifactId>
|
||||
<version>${groovy-all.version}</version>
|
||||
<type>pom</type>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.groovy</groupId>
|
||||
<artifactId>groovy-dateutil</artifactId>
|
||||
<version>${groovy.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.groovy</groupId>
|
||||
<artifactId>groovy-sql</artifactId>
|
||||
<version>${groovy-sql.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-runner</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hsqldb</groupId>
|
||||
<artifactId>hsqldb</artifactId>
|
||||
<version>${hsqldb.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.spockframework</groupId>
|
||||
<artifactId>spock-core</artifactId>
|
||||
<version>${spock-core.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.gmavenplus</groupId>
|
||||
<artifactId>gmavenplus-plugin</artifactId>
|
||||
<version>${gmavenplus-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>addSources</goal>
|
||||
<goal>addTestSources</goal>
|
||||
<goal>compile</goal>
|
||||
<goal>compileTests</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-failsafe-plugin</artifactId>
|
||||
<version>${maven-failsafe-plugin.version}</version>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-surefire-provider</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>junit5</id>
|
||||
<goals>
|
||||
<goal>integration-test</goal>
|
||||
<goal>verify</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<includes>
|
||||
<include>**/*Test5.java</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.20.1</version>
|
||||
<configuration>
|
||||
<useFile>false</useFile>
|
||||
<includes>
|
||||
<include>**/*Test.java</include>
|
||||
<include>**/*Spec.java</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>central</id>
|
||||
<url>http://jcenter.bintray.com</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
<properties>
|
||||
<junit.platform.version>1.0.0</junit.platform.version>
|
||||
<groovy.version>2.5.6</groovy.version>
|
||||
<groovy-all.version>2.5.6</groovy-all.version>
|
||||
<groovy-sql.version>2.5.6</groovy-sql.version>
|
||||
<hsqldb.version>2.4.0</hsqldb.version>
|
||||
<spock-core.version>1.1-groovy-2.4</spock-core.version>
|
||||
<gmavenplus-plugin.version>1.6</gmavenplus-plugin.version>
|
||||
</properties>
|
||||
</project>
|
||||
|
|
@ -0,0 +1,79 @@
|
|||
package com.baeldung.defkeyword
|
||||
|
||||
import org.codehaus.groovy.runtime.NullObject
|
||||
import org.codehaus.groovy.runtime.typehandling.GroovyCastException
|
||||
|
||||
import groovy.transform.TypeChecked
|
||||
import groovy.transform.TypeCheckingMode
|
||||
|
||||
@TypeChecked
|
||||
class DefUnitTest extends GroovyTestCase {
|
||||
|
||||
def id
|
||||
def firstName = "Samwell"
|
||||
def listOfCountries = ['USA', 'UK', 'FRANCE', 'INDIA']
|
||||
|
||||
@TypeChecked(TypeCheckingMode.SKIP)
|
||||
def multiply(x, y) {
|
||||
return x*y
|
||||
}
|
||||
|
||||
@TypeChecked(TypeCheckingMode.SKIP)
|
||||
void testDefVariableDeclaration() {
|
||||
|
||||
def list
|
||||
assert list.getClass() == org.codehaus.groovy.runtime.NullObject
|
||||
assert list.is(null)
|
||||
|
||||
list = [1,2,4]
|
||||
assert list instanceof ArrayList
|
||||
}
|
||||
|
||||
@TypeChecked(TypeCheckingMode.SKIP)
|
||||
void testTypeVariables() {
|
||||
int rate = 200
|
||||
try {
|
||||
rate = [12] //GroovyCastException
|
||||
rate = "nill" //GroovyCastException
|
||||
} catch(GroovyCastException) {
|
||||
println "Cannot assign anything other than integer"
|
||||
}
|
||||
}
|
||||
|
||||
@TypeChecked(TypeCheckingMode.SKIP)
|
||||
void testDefVariableMultipleAssignment() {
|
||||
def rate
|
||||
assert rate == null
|
||||
assert rate.getClass() == org.codehaus.groovy.runtime.NullObject
|
||||
|
||||
rate = 12
|
||||
assert rate instanceof Integer
|
||||
|
||||
rate = "Not Available"
|
||||
assert rate instanceof String
|
||||
|
||||
rate = [1, 4]
|
||||
assert rate instanceof List
|
||||
|
||||
assert divide(12, 3) instanceof BigDecimal
|
||||
assert divide(1, 0) instanceof String
|
||||
|
||||
}
|
||||
|
||||
def divide(int x, int y) {
|
||||
if(y==0) {
|
||||
return "Should not divide by 0"
|
||||
} else {
|
||||
return x/y
|
||||
}
|
||||
}
|
||||
|
||||
def greetMsg() {
|
||||
println "Hello! I am Groovy"
|
||||
}
|
||||
|
||||
void testDefVsType() {
|
||||
def int count
|
||||
assert count instanceof Integer
|
||||
}
|
||||
}
|
|
@ -0,0 +1,44 @@
|
|||
package com.baeldung.strings
|
||||
|
||||
import spock.lang.Specification
|
||||
|
||||
import java.util.regex.Pattern
|
||||
|
||||
class StringMatchingSpec extends Specification {
|
||||
|
||||
def "pattern operator example"() {
|
||||
given: "a pattern"
|
||||
def p = ~'foo'
|
||||
|
||||
expect:
|
||||
p instanceof Pattern
|
||||
|
||||
and: "you can use slash strings to avoid escaping of blackslash"
|
||||
def digitPattern = ~/\d*/
|
||||
digitPattern.matcher('4711').matches()
|
||||
}
|
||||
|
||||
def "match operator example"() {
|
||||
expect:
|
||||
'foobar' ==~ /.*oba.*/
|
||||
|
||||
and: "matching is strict"
|
||||
!('foobar' ==~ /foo/)
|
||||
}
|
||||
|
||||
def "find operator example"() {
|
||||
when: "using the find operator"
|
||||
def matcher = 'foo and bar, baz and buz' =~ /(\w+) and (\w+)/
|
||||
|
||||
then: "will find groups"
|
||||
matcher.size() == 2
|
||||
|
||||
and: "can access groups using array"
|
||||
matcher[0][0] == 'foo and bar'
|
||||
matcher[1][2] == 'buz'
|
||||
|
||||
and: "you can use it as a predicate"
|
||||
'foobarbaz' =~ /bar/
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,6 @@
|
|||
# Groovy
|
||||
|
||||
## Relevant articles:
|
||||
|
||||
- [Maps in Groovy](http://www.baeldung.com/)
|
||||
|
|
@ -0,0 +1,131 @@
|
|||
<?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-groovy-collections</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<name>core-groovy-collections</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.groovy</groupId>
|
||||
<artifactId>groovy</artifactId>
|
||||
<version>${groovy.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.groovy</groupId>
|
||||
<artifactId>groovy-all</artifactId>
|
||||
<version>${groovy-all.version}</version>
|
||||
<type>pom</type>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.groovy</groupId>
|
||||
<artifactId>groovy-dateutil</artifactId>
|
||||
<version>${groovy.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.groovy</groupId>
|
||||
<artifactId>groovy-sql</artifactId>
|
||||
<version>${groovy-sql.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-runner</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hsqldb</groupId>
|
||||
<artifactId>hsqldb</artifactId>
|
||||
<version>${hsqldb.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.spockframework</groupId>
|
||||
<artifactId>spock-core</artifactId>
|
||||
<version>${spock-core.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.gmavenplus</groupId>
|
||||
<artifactId>gmavenplus-plugin</artifactId>
|
||||
<version>${gmavenplus-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>addSources</goal>
|
||||
<goal>addTestSources</goal>
|
||||
<goal>compile</goal>
|
||||
<goal>compileTests</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-failsafe-plugin</artifactId>
|
||||
<version>${maven-failsafe-plugin.version}</version>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-surefire-provider</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>junit5</id>
|
||||
<goals>
|
||||
<goal>integration-test</goal>
|
||||
<goal>verify</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<includes>
|
||||
<include>**/*Test5.java</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.20.1</version>
|
||||
<configuration>
|
||||
<useFile>false</useFile>
|
||||
<includes>
|
||||
<include>**/*Test.java</include>
|
||||
<include>**/*Spec.java</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>central</id>
|
||||
<url>http://jcenter.bintray.com</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
<properties>
|
||||
<junit.platform.version>1.0.0</junit.platform.version>
|
||||
<groovy.version>2.5.6</groovy.version>
|
||||
<groovy-all.version>2.5.6</groovy-all.version>
|
||||
<groovy-sql.version>2.5.6</groovy-sql.version>
|
||||
<hsqldb.version>2.4.0</hsqldb.version>
|
||||
<spock-core.version>1.1-groovy-2.4</spock-core.version>
|
||||
<gmavenplus-plugin.version>1.6</gmavenplus-plugin.version>
|
||||
</properties>
|
||||
</project>
|
||||
|
|
@ -0,0 +1,148 @@
|
|||
package com.baeldung.map;
|
||||
|
||||
import static groovy.test.GroovyAssert.*
|
||||
import org.junit.Test
|
||||
|
||||
class MapTest{
|
||||
|
||||
@Test
|
||||
void createMap() {
|
||||
|
||||
def emptyMap = [:]
|
||||
assertNotNull(emptyMap)
|
||||
|
||||
assertTrue(emptyMap instanceof java.util.LinkedHashMap)
|
||||
|
||||
def map = [name:"Jerry", age: 42, city: "New York"]
|
||||
assertTrue(map.size() == 3)
|
||||
}
|
||||
|
||||
@Test
|
||||
void addItemsToMap() {
|
||||
|
||||
def map = [name:"Jerry"]
|
||||
|
||||
map["age"] = 42
|
||||
|
||||
map.city = "New York"
|
||||
|
||||
def hobbyLiteral = "hobby"
|
||||
def hobbyMap = [(hobbyLiteral): "Singing"]
|
||||
map.putAll(hobbyMap)
|
||||
|
||||
assertTrue(map == [name:"Jerry", age: 42, city: "New York", hobby:"Singing"])
|
||||
assertTrue(hobbyMap.hobby == "Singing")
|
||||
assertTrue(hobbyMap[hobbyLiteral] == "Singing")
|
||||
|
||||
map.plus([1:20]) // returns new map
|
||||
|
||||
map << [2:30]
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
void getItemsFromMap() {
|
||||
|
||||
def map = [name:"Jerry", age: 42, city: "New York", hobby:"Singing"]
|
||||
|
||||
assertTrue(map["name"] == "Jerry")
|
||||
|
||||
assertTrue(map.name == "Jerry")
|
||||
|
||||
def propertyAge = "age"
|
||||
assertTrue(map[propertyAge] == 42)
|
||||
}
|
||||
|
||||
@Test
|
||||
void removeItemsFromMap() {
|
||||
|
||||
def map = [1:20, a:30, 2:42, 4:34, ba:67, 6:39, 7:49]
|
||||
|
||||
def minusMap = map.minus([2:42, 4:34]);
|
||||
assertTrue(minusMap == [1:20, a:30, ba:67, 6:39, 7:49])
|
||||
|
||||
minusMap.removeAll{it -> it.key instanceof String}
|
||||
assertTrue( minusMap == [ 1:20, 6:39, 7:49])
|
||||
|
||||
minusMap.retainAll{it -> it.value %2 == 0}
|
||||
assertTrue( minusMap == [1:20])
|
||||
}
|
||||
|
||||
@Test
|
||||
void iteratingOnMaps(){
|
||||
def map = [name:"Jerry", age: 42, city: "New York", hobby:"Singing"]
|
||||
|
||||
map.each{ entry -> println "$entry.key: $entry.value" }
|
||||
|
||||
map.eachWithIndex{ entry, i -> println "$i $entry.key: $entry.value" }
|
||||
|
||||
map.eachWithIndex{ key, value, i -> println "$i $key: $value" }
|
||||
}
|
||||
|
||||
@Test
|
||||
void filteringAndSearchingMaps(){
|
||||
def map = [name:"Jerry", age: 42, city: "New York", hobby:"Singing"]
|
||||
|
||||
assertTrue(map.find{ it.value == "New York"}.key == "city")
|
||||
|
||||
assertTrue(map.findAll{ it.value == "New York"} == [city : "New York"])
|
||||
|
||||
map.grep{it.value == "New York"}.each{ it -> assertTrue(it.key == "city" && it.value == "New York")}
|
||||
|
||||
assertTrue(map.every{it -> it.value instanceof String} == false)
|
||||
|
||||
assertTrue(map.any{it -> it.value instanceof String} == true)
|
||||
}
|
||||
|
||||
@Test
|
||||
void collect(){
|
||||
|
||||
def map = [1: [name:"Jerry", age: 42, city: "New York"],
|
||||
2: [name:"Long", age: 25, city: "New York"],
|
||||
3: [name:"Dustin", age: 29, city: "New York"],
|
||||
4: [name:"Dustin", age: 34, city: "New York"]]
|
||||
|
||||
def names = map.collect{entry -> entry.value.name} // returns only list
|
||||
assertTrue(names == ["Jerry", "Long", "Dustin", "Dustin"])
|
||||
|
||||
def uniqueNames = map.collect([] as HashSet){entry -> entry.value.name}
|
||||
assertTrue(uniqueNames == ["Jerry", "Long", "Dustin"] as Set)
|
||||
|
||||
def idNames = map.collectEntries{key, value -> [key, value.name]}
|
||||
assertTrue(idNames == [1:"Jerry", 2: "Long", 3:"Dustin", 4: "Dustin"])
|
||||
|
||||
def below30Names = map.findAll{it.value.age < 30}.collect{key, value -> value.name}
|
||||
assertTrue(below30Names == ["Long", "Dustin"])
|
||||
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
void group(){
|
||||
def map = [1:20, 2: 40, 3: 11, 4: 93]
|
||||
|
||||
def subMap = map.groupBy{it.value % 2}
|
||||
println subMap
|
||||
assertTrue(subMap == [0:[1:20, 2:40 ], 1:[3:11, 4:93]])
|
||||
|
||||
def keySubMap = map.subMap([1, 2])
|
||||
assertTrue(keySubMap == [1:20, 2:40])
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
void sorting(){
|
||||
def map = [ab:20, a: 40, cb: 11, ba: 93]
|
||||
|
||||
def naturallyOrderedMap = map.sort()
|
||||
assertTrue([a:40, ab:20, ba:93, cb:11] == naturallyOrderedMap)
|
||||
|
||||
def compSortedMap = map.sort({ k1, k2 -> k1 <=> k2 } as Comparator)
|
||||
assertTrue([a:40, ab:20, ba:93, cb:11] == compSortedMap)
|
||||
|
||||
def cloSortedMap = map.sort({ it1, it2 -> it1.value <=> it1.value })
|
||||
assertTrue([cb:11, ab:20, a:40, ba:93] == cloSortedMap)
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -8,4 +8,8 @@
|
|||
- [Types of Strings in Groovy](https://www.baeldung.com/groovy-strings)
|
||||
- [A Quick Guide to Iterating a Map in Groovy](https://www.baeldung.com/groovy-map-iterating)
|
||||
- [An Introduction to Traits in Groovy](https://www.baeldung.com/groovy-traits)
|
||||
- [Closures in Groovy](https://www.baeldung.com/groovy-closures)
|
||||
- [Finding Elements in Collections in Groovy](https://www.baeldung.com/groovy-collections-find-elements)
|
||||
- [Lists in Groovy](https://www.baeldung.com/groovy-lists)
|
||||
- [Converting a String to a Date in Groovy](https://www.baeldung.com/groovy-string-to-date)
|
||||
- [Guide to I/O in Groovy](https://www.baeldung.com/groovy-io)
|
|
@ -0,0 +1,37 @@
|
|||
package com.baeldung
|
||||
|
||||
class Person {
|
||||
private String firstname
|
||||
private String lastname
|
||||
private Integer age
|
||||
|
||||
Person(String firstname, String lastname, Integer age) {
|
||||
this.firstname = firstname
|
||||
this.lastname = lastname
|
||||
this.age = age
|
||||
}
|
||||
|
||||
String getFirstname() {
|
||||
return firstname
|
||||
}
|
||||
|
||||
void setFirstname(String firstname) {
|
||||
this.firstname = firstname
|
||||
}
|
||||
|
||||
String getLastname() {
|
||||
return lastname
|
||||
}
|
||||
|
||||
void setLastname(String lastname) {
|
||||
this.lastname = lastname
|
||||
}
|
||||
|
||||
Integer getAge() {
|
||||
return age
|
||||
}
|
||||
|
||||
void setAge(Integer age) {
|
||||
this.age = age
|
||||
}
|
||||
}
|
|
@ -0,0 +1,87 @@
|
|||
package com.baeldung.closures
|
||||
|
||||
class Closures {
|
||||
|
||||
def printWelcome = {
|
||||
println "Welcome to Closures!"
|
||||
}
|
||||
|
||||
def print = { name ->
|
||||
println name
|
||||
}
|
||||
|
||||
def formatToLowerCase(name) {
|
||||
return name.toLowerCase()
|
||||
}
|
||||
def formatToLowerCaseClosure = { name ->
|
||||
return name.toLowerCase()
|
||||
}
|
||||
|
||||
def count=0
|
||||
|
||||
def increaseCount = {
|
||||
count++
|
||||
}
|
||||
|
||||
def greet = {
|
||||
return "Hello! ${it}"
|
||||
}
|
||||
|
||||
def multiply = { x, y ->
|
||||
return x*y
|
||||
}
|
||||
|
||||
def calculate = {int x, int y, String operation ->
|
||||
|
||||
//log closure
|
||||
def log = {
|
||||
println "Performing $it"
|
||||
}
|
||||
|
||||
def result = 0
|
||||
switch(operation) {
|
||||
case "ADD":
|
||||
log("Addition")
|
||||
result = x+y
|
||||
break
|
||||
case "SUB":
|
||||
log("Subtraction")
|
||||
result = x-y
|
||||
break
|
||||
case "MUL":
|
||||
log("Multiplication")
|
||||
result = x*y
|
||||
break
|
||||
case "DIV":
|
||||
log("Division")
|
||||
result = x/y
|
||||
break
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
def addAll = { int... args ->
|
||||
return args.sum()
|
||||
}
|
||||
|
||||
def volume(Closure areaCalculator, int... dimensions) {
|
||||
if(dimensions.size() == 3) {
|
||||
|
||||
//consider dimension[0] = length, dimension[1] = breadth, dimension[2] = height
|
||||
//for cube and cuboid
|
||||
return areaCalculator(dimensions[0], dimensions[1]) * dimensions[2]
|
||||
} else if(dimensions.size() == 2) {
|
||||
|
||||
//consider dimension[0] = radius, dimension[1] = height
|
||||
//for cylinder and cone
|
||||
return areaCalculator(dimensions[0]) * dimensions[1]
|
||||
} else if(dimensions.size() == 1) {
|
||||
|
||||
//consider dimension[0] = radius
|
||||
//for sphere
|
||||
return areaCalculator(dimensions[0]) * dimensions[0]
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,6 @@
|
|||
package com.baeldung.closures
|
||||
|
||||
class Employee {
|
||||
|
||||
String fullName
|
||||
}
|
|
@ -0,0 +1,80 @@
|
|||
package com.baeldung.closures
|
||||
|
||||
import spock.lang.Specification
|
||||
|
||||
class ClosuresUnitTest extends GroovyTestCase {
|
||||
|
||||
Closures closures = new Closures()
|
||||
|
||||
void testDeclaration() {
|
||||
|
||||
closures.print("Hello! Closure")
|
||||
closures.formatToLowerCaseClosure("Hello! Closure")
|
||||
|
||||
closures.print.call("Hello! Closure")
|
||||
closures.formatToLowerCaseClosure.call("Hello! Closure")
|
||||
|
||||
}
|
||||
|
||||
void testClosureVsMethods() {
|
||||
assert closures.formatToLowerCase("TONY STARK") == closures.formatToLowerCaseClosure("Tony STark")
|
||||
}
|
||||
|
||||
void testParameters() {
|
||||
//implicit parameter
|
||||
assert closures.greet("Alex") == "Hello! Alex"
|
||||
|
||||
//multiple parameters
|
||||
assert closures.multiply(2, 4) == 8
|
||||
|
||||
assert closures.calculate(12, 4, "ADD") == 16
|
||||
assert closures.calculate(12, 4, "SUB") == 8
|
||||
assert closures.calculate(43, 8, "DIV") == 5.375
|
||||
|
||||
//varags
|
||||
assert closures.addAll(12, 10, 14) == 36
|
||||
|
||||
}
|
||||
|
||||
void testClosureAsAnArgument() {
|
||||
assert closures.volume({ l, b -> return l*b }, 12, 6, 10) == 720
|
||||
|
||||
assert closures.volume({ radius -> return Math.PI*radius*radius/3 }, 5, 10) == Math.PI * 250/3
|
||||
}
|
||||
|
||||
void testGStringsLazyEvaluation() {
|
||||
def name = "Samwell"
|
||||
def welcomeMsg = "Welcome! $name"
|
||||
|
||||
assert welcomeMsg == "Welcome! Samwell"
|
||||
|
||||
// changing the name does not affect original interpolated value
|
||||
name = "Tarly"
|
||||
assert welcomeMsg != "Welcome! Tarly"
|
||||
|
||||
def fullName = "Tarly Samson"
|
||||
def greetStr = "Hello! ${-> fullName}"
|
||||
|
||||
assert greetStr == "Hello! Tarly Samson"
|
||||
|
||||
// this time changing the variable affects the interpolated String's value
|
||||
fullName = "Jon Smith"
|
||||
assert greetStr == "Hello! Jon Smith"
|
||||
}
|
||||
|
||||
void testClosureInLists() {
|
||||
def list = [10, 11, 12, 13, 14, true, false, "BUNTHER"]
|
||||
list.each {
|
||||
println it
|
||||
}
|
||||
|
||||
assert [13, 14] == list.findAll{ it instanceof Integer && it >= 13}
|
||||
}
|
||||
|
||||
void testClosureInMaps() {
|
||||
def map = [1:10, 2:30, 4:5]
|
||||
|
||||
assert [10, 60, 20] == map.collect{it.key * it.value}
|
||||
}
|
||||
|
||||
}
|
|
@ -129,13 +129,13 @@ class ListTest{
|
|||
assertTrue(filterList.findAll{it > 3} == [4, 5, 6, 76])
|
||||
|
||||
assertTrue(filterList.findAll{ it instanceof Number} == [2, 1, 3, 4, 5, 6, 76])
|
||||
|
||||
|
||||
assertTrue(filterList.grep( Number )== [2, 1, 3, 4, 5, 6, 76])
|
||||
|
||||
|
||||
assertTrue(filterList.grep{ it> 6 }== [76])
|
||||
|
||||
def conditionList = [2, 1, 3, 4, 5, 6, 76]
|
||||
|
||||
|
||||
assertFalse(conditionList.every{ it < 6})
|
||||
|
||||
assertTrue(conditionList.any{ it%2 == 0})
|
||||
|
@ -165,7 +165,7 @@ class ListTest{
|
|||
|
||||
def strList = ["na", "ppp", "as"]
|
||||
assertTrue(strList.max() == "ppp")
|
||||
|
||||
|
||||
Comparator minc = {a,b -> a == b? 0: a < b? -1 : 1}
|
||||
def numberList = [3, 2, 0, 7]
|
||||
assertTrue(numberList.min(minc) == 0)
|
||||
|
|
|
@ -0,0 +1,58 @@
|
|||
package com.baeldung.lists
|
||||
|
||||
import com.baeldung.Person
|
||||
import org.junit.Test
|
||||
|
||||
import static org.junit.Assert.*
|
||||
|
||||
class ListUnitTest {
|
||||
|
||||
private final personList = [
|
||||
new Person("Regina", "Fitzpatrick", 25),
|
||||
new Person("Abagail", "Ballard", 26),
|
||||
new Person("Lucian", "Walter", 30),
|
||||
]
|
||||
|
||||
@Test
|
||||
void whenListContainsElement_thenCheckReturnsTrue() {
|
||||
def list = ['a', 'b', 'c']
|
||||
|
||||
assertTrue(list.indexOf('a') > -1)
|
||||
assertTrue(list.contains('a'))
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenListContainsElement_thenCheckWithMembershipOperatorReturnsTrue() {
|
||||
def list = ['a', 'b', 'c']
|
||||
|
||||
assertTrue('a' in list)
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenListOfPerson_whenUsingStreamMatching_thenShouldEvaluateList() {
|
||||
assertTrue(personList.stream().anyMatch {it.age > 20})
|
||||
assertFalse(personList.stream().allMatch {it.age < 30})
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenListOfPerson_whenUsingCollectionMatching_thenShouldEvaluateList() {
|
||||
assertTrue(personList.any {it.age > 20})
|
||||
assertFalse(personList.every {it.age < 30})
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenListOfPerson_whenUsingStreamFind_thenShouldReturnMatchingElements() {
|
||||
assertTrue(personList.stream().filter {it.age > 20}.findAny().isPresent())
|
||||
assertFalse(personList.stream().filter {it.age > 30}.findAny().isPresent())
|
||||
assertTrue(personList.stream().filter {it.age > 20}.findAll().size() == 3)
|
||||
assertTrue(personList.stream().filter {it.age > 30}.findAll().isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenListOfPerson_whenUsingCollectionFind_thenShouldReturnMatchingElements() {
|
||||
assertNotNull(personList.find {it.age > 20})
|
||||
assertNull(personList.find {it.age > 30})
|
||||
assertTrue(personList.findAll {it.age > 20}.size() == 3)
|
||||
assertTrue(personList.findAll {it.age > 30}.isEmpty())
|
||||
}
|
||||
}
|
|
@ -0,0 +1,148 @@
|
|||
package com.baeldung.groovy.map;
|
||||
|
||||
import static groovy.test.GroovyAssert.*
|
||||
import org.junit.Test
|
||||
|
||||
class MapTest{
|
||||
|
||||
@Test
|
||||
void createMap() {
|
||||
|
||||
def emptyMap = [:]
|
||||
assertNotNull(emptyMap)
|
||||
|
||||
assertTrue(emptyMap instanceof java.util.LinkedHashMap)
|
||||
|
||||
def map = [name:"Jerry", age: 42, city: "New York"]
|
||||
assertTrue(map.size() == 3)
|
||||
}
|
||||
|
||||
@Test
|
||||
void addItemsToMap() {
|
||||
|
||||
def map = [name:"Jerry"]
|
||||
|
||||
map["age"] = 42
|
||||
|
||||
map.city = "New York"
|
||||
|
||||
def hobbyLiteral = "hobby"
|
||||
def hobbyMap = [(hobbyLiteral): "Singing"]
|
||||
map.putAll(hobbyMap)
|
||||
|
||||
assertTrue(map == [name:"Jerry", age: 42, city: "New York", hobby:"Singing"])
|
||||
assertTrue(hobbyMap.hobby == "Singing")
|
||||
assertTrue(hobbyMap[hobbyLiteral] == "Singing")
|
||||
|
||||
map.plus([1:20]) // returns new map
|
||||
|
||||
map << [2:30]
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
void getItemsFromMap() {
|
||||
|
||||
def map = [name:"Jerry", age: 42, city: "New York", hobby:"Singing"]
|
||||
|
||||
assertTrue(map["name"] == "Jerry")
|
||||
|
||||
assertTrue(map.name == "Jerry")
|
||||
|
||||
def propertyAge = "age"
|
||||
assertTrue(map[propertyAge] == 42)
|
||||
}
|
||||
|
||||
@Test
|
||||
void removeItemsFromMap() {
|
||||
|
||||
def map = [1:20, a:30, 2:42, 4:34, ba:67, 6:39, 7:49]
|
||||
|
||||
def minusMap = map.minus([2:42, 4:34]);
|
||||
assertTrue(minusMap == [1:20, a:30, ba:67, 6:39, 7:49])
|
||||
|
||||
minusMap.removeAll{it -> it.key instanceof String}
|
||||
assertTrue( minusMap == [ 1:20, 6:39, 7:49])
|
||||
|
||||
minusMap.retainAll{it -> it.value %2 == 0}
|
||||
assertTrue( minusMap == [1:20])
|
||||
}
|
||||
|
||||
@Test
|
||||
void iteratingOnMaps(){
|
||||
def map = [name:"Jerry", age: 42, city: "New York", hobby:"Singing"]
|
||||
|
||||
map.each{ entry -> println "$entry.key: $entry.value" }
|
||||
|
||||
map.eachWithIndex{ entry, i -> println "$i $entry.key: $entry.value" }
|
||||
|
||||
map.eachWithIndex{ key, value, i -> println "$i $key: $value" }
|
||||
}
|
||||
|
||||
@Test
|
||||
void filteringAndSearchingMaps(){
|
||||
def map = [name:"Jerry", age: 42, city: "New York", hobby:"Singing"]
|
||||
|
||||
assertTrue(map.find{ it.value == "New York"}.key == "city")
|
||||
|
||||
assertTrue(map.findAll{ it.value == "New York"} == [city : "New York"])
|
||||
|
||||
map.grep{it.value == "New York"}.each{ it -> assertTrue(it.key == "city" && it.value == "New York")}
|
||||
|
||||
assertTrue(map.every{it -> it.value instanceof String} == false)
|
||||
|
||||
assertTrue(map.any{it -> it.value instanceof String} == true)
|
||||
}
|
||||
|
||||
@Test
|
||||
void collect(){
|
||||
|
||||
def map = [1: [name:"Jerry", age: 42, city: "New York"],
|
||||
2: [name:"Long", age: 25, city: "New York"],
|
||||
3: [name:"Dustin", age: 29, city: "New York"],
|
||||
4: [name:"Dustin", age: 34, city: "New York"]]
|
||||
|
||||
def names = map.collect{entry -> entry.value.name} // returns only list
|
||||
assertTrue(names == ["Jerry", "Long", "Dustin", "Dustin"])
|
||||
|
||||
def uniqueNames = map.collect([] as HashSet){entry -> entry.value.name}
|
||||
assertTrue(uniqueNames == ["Jerry", "Long", "Dustin"] as Set)
|
||||
|
||||
def idNames = map.collectEntries{key, value -> [key, value.name]}
|
||||
assertTrue(idNames == [1:"Jerry", 2: "Long", 3:"Dustin", 4: "Dustin"])
|
||||
|
||||
def below30Names = map.findAll{it.value.age < 30}.collect{key, value -> value.name}
|
||||
assertTrue(below30Names == ["Long", "Dustin"])
|
||||
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
void group(){
|
||||
def map = [1:20, 2: 40, 3: 11, 4: 93]
|
||||
|
||||
def subMap = map.groupBy{it.value % 2}
|
||||
println subMap
|
||||
assertTrue(subMap == [0:[1:20, 2:40 ], 1:[3:11, 4:93]])
|
||||
|
||||
def keySubMap = map.subMap([1, 2])
|
||||
assertTrue(keySubMap == [1:20, 2:40])
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
void sorting(){
|
||||
def map = [ab:20, a: 40, cb: 11, ba: 93]
|
||||
|
||||
def naturallyOrderedMap = map.sort()
|
||||
assertTrue([a:40, ab:20, ba:93, cb:11] == naturallyOrderedMap)
|
||||
|
||||
def compSortedMap = map.sort({ k1, k2 -> k1 <=> k2 } as Comparator)
|
||||
assertTrue([a:40, ab:20, ba:93, cb:11] == compSortedMap)
|
||||
|
||||
def cloSortedMap = map.sort({ it1, it2 -> it1.value <=> it1.value })
|
||||
assertTrue([cb:11, ab:20, a:40, ba:93] == cloSortedMap)
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -1,10 +1,18 @@
|
|||
package com.baeldung.map
|
||||
|
||||
import static org.junit.Assert.*
|
||||
import com.baeldung.Person
|
||||
import org.junit.Test
|
||||
|
||||
import static org.junit.Assert.*
|
||||
|
||||
class MapUnitTest {
|
||||
|
||||
private final personMap = [
|
||||
Regina : new Person("Regina", "Fitzpatrick", 25),
|
||||
Abagail: new Person("Abagail", "Ballard", 26),
|
||||
Lucian : new Person("Lucian", "Walter", 30)
|
||||
]
|
||||
|
||||
@Test
|
||||
void whenUsingEach_thenMapIsIterated() {
|
||||
def map = [
|
||||
|
@ -63,7 +71,7 @@ class MapUnitTest {
|
|||
'FF6347' : 'Tomato',
|
||||
'FF4500' : 'Orange Red'
|
||||
]
|
||||
|
||||
|
||||
map.eachWithIndex { key, val, index ->
|
||||
def indent = ((index == 0 || index % 2 == 0) ? " " : "")
|
||||
println "$indent Hex Code: $key = Color Name: $val"
|
||||
|
@ -82,4 +90,65 @@ class MapUnitTest {
|
|||
println "Hex Code: $entry.key = Color Name: $entry.value"
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenMapContainsKeyElement_thenCheckReturnsTrue() {
|
||||
def map = [a: 'd', b: 'e', c: 'f']
|
||||
|
||||
assertTrue(map.containsKey('a'))
|
||||
assertFalse(map.containsKey('e'))
|
||||
assertTrue(map.containsValue('e'))
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenMapContainsKeyElement_thenCheckByMembershipReturnsTrue() {
|
||||
def map = [a: 'd', b: 'e', c: 'f']
|
||||
|
||||
assertTrue('a' in map)
|
||||
assertFalse('f' in map)
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenMapContainsFalseBooleanValues_thenCheckReturnsFalse() {
|
||||
def map = [a: true, b: false, c: null]
|
||||
|
||||
assertTrue(map.containsKey('b'))
|
||||
assertTrue('a' in map)
|
||||
assertFalse('b' in map)
|
||||
assertFalse('c' in map)
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMapOfPerson_whenUsingStreamMatching_thenShouldEvaluateMap() {
|
||||
assertTrue(personMap.keySet().stream().anyMatch {it == "Regina"})
|
||||
assertFalse(personMap.keySet().stream().allMatch {it == "Albert"})
|
||||
assertFalse(personMap.values().stream().allMatch {it.age < 30})
|
||||
assertTrue(personMap.entrySet().stream().anyMatch {it.key == "Abagail" && it.value.lastname == "Ballard"})
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMapOfPerson_whenUsingCollectionMatching_thenShouldEvaluateMap() {
|
||||
assertTrue(personMap.keySet().any {it == "Regina"})
|
||||
assertFalse(personMap.keySet().every {it == "Albert"})
|
||||
assertFalse(personMap.values().every {it.age < 30})
|
||||
assertTrue(personMap.any {firstname, person -> firstname == "Abagail" && person.lastname == "Ballard"})
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMapOfPerson_whenUsingCollectionFind_thenShouldReturnElements() {
|
||||
assertNotNull(personMap.find {it.key == "Abagail" && it.value.lastname == "Ballard"})
|
||||
assertTrue(personMap.findAll {it.value.age > 20}.size() == 3)
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMapOfPerson_whenUsingStreamFind_thenShouldReturnElements() {
|
||||
assertTrue(
|
||||
personMap.entrySet().stream()
|
||||
.filter {it.key == "Abagail" && it.value.lastname == "Ballard"}
|
||||
.findAny().isPresent())
|
||||
assertTrue(
|
||||
personMap.entrySet().stream()
|
||||
.filter {it.value.age > 20}
|
||||
.findAll().size() == 3)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,16 @@
|
|||
package com.baeldung.set
|
||||
|
||||
import org.junit.Test
|
||||
|
||||
import static org.junit.Assert.assertTrue
|
||||
|
||||
class SetUnitTest {
|
||||
|
||||
@Test
|
||||
void whenSetContainsElement_thenCheckReturnsTrue() {
|
||||
def set = ['a', 'b', 'c'] as Set
|
||||
|
||||
assertTrue(set.contains('a'))
|
||||
assertTrue('a' in set)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,44 @@
|
|||
package com.baeldung.strings
|
||||
|
||||
import spock.lang.Specification
|
||||
|
||||
import java.util.regex.Pattern
|
||||
|
||||
class StringMatchingSpec extends Specification {
|
||||
|
||||
def "pattern operator example"() {
|
||||
given: "a pattern"
|
||||
def p = ~'foo'
|
||||
|
||||
expect:
|
||||
p instanceof Pattern
|
||||
|
||||
and: "you can use slash strings to avoid escaping of blackslash"
|
||||
def digitPattern = ~/\d*/
|
||||
digitPattern.matcher('4711').matches()
|
||||
}
|
||||
|
||||
def "match operator example"() {
|
||||
expect:
|
||||
'foobar' ==~ /.*oba.*/
|
||||
|
||||
and: "matching is strict"
|
||||
!('foobar' ==~ /foo/)
|
||||
}
|
||||
|
||||
def "find operator example"() {
|
||||
when: "using the find operator"
|
||||
def matcher = 'foo and bar, baz and buz' =~ /(\w+) and (\w+)/
|
||||
|
||||
then: "will find groups"
|
||||
matcher.size() == 2
|
||||
|
||||
and: "can access groups using array"
|
||||
matcher[0][0] == 'foo and bar'
|
||||
matcher[1][2] == 'buz'
|
||||
|
||||
and: "you can use it as a predicate"
|
||||
'foobarbaz' =~ /bar/
|
||||
}
|
||||
|
||||
}
|
|
@ -4,3 +4,6 @@
|
|||
- [Java 11 Local Variable Syntax for Lambda Parameters](https://www.baeldung.com/java-var-lambda-params)
|
||||
- [Java 11 String API Additions](https://www.baeldung.com/java-11-string-api)
|
||||
- [Java 11 Nest Based Access Control](https://www.baeldung.com/java-nest-based-access-control)
|
||||
- [Exploring the New HTTP Client in Java 9 and 11](https://www.baeldung.com/java-9-http-client)
|
||||
- [An Introduction to Epsilon GC: A No-Op Experimental Garbage Collector](https://www.baeldung.com/jvm-epsilon-gc-garbage-collector)
|
||||
- [Guide to jlink](https://www.baeldung.com/jlink)
|
||||
|
|
|
@ -14,6 +14,14 @@
|
|||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
|
@ -31,6 +39,7 @@
|
|||
<properties>
|
||||
<maven.compiler.source.version>11</maven.compiler.source.version>
|
||||
<maven.compiler.target.version>11</maven.compiler.target.version>
|
||||
<guava.version>27.1-jre</guava.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -0,0 +1,12 @@
|
|||
package com.baeldung.jlink;
|
||||
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class HelloWorld {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(HelloWorld.class.getName());
|
||||
|
||||
public static void main(String[] args) {
|
||||
LOG.info("Hello World!");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
module jlinkModule {
|
||||
requires java.logging;
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
package com.baeldung;
|
||||
|
||||
import com.google.common.base.Strings;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
public class EmptyStringToEmptyOptionalUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenEmptyString_whenFilteringOnOptional_thenEmptyOptionalIsReturned() {
|
||||
String str = "";
|
||||
Optional<String> opt = Optional.ofNullable(str).filter(s -> !s.isEmpty());
|
||||
Assert.assertFalse(opt.isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyString_whenFilteringOnOptionalInJava11_thenEmptyOptionalIsReturned() {
|
||||
String str = "";
|
||||
Optional<String> opt = Optional.ofNullable(str).filter(Predicate.not(String::isEmpty));
|
||||
Assert.assertFalse(opt.isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyString_whenPassingResultOfEmptyToNullToOfNullable_thenEmptyOptionalIsReturned() {
|
||||
String str = "";
|
||||
Optional<String> opt = Optional.ofNullable(Strings.emptyToNull(str));
|
||||
Assert.assertFalse(opt.isPresent());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,49 @@
|
|||
<?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>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<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>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${maven.compiler.source.version}</source>
|
||||
<target>${maven.compiler.target.version}</target>
|
||||
<compilerArgs>--enable-preview</compilerArgs>
|
||||
</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>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,71 @@
|
|||
package com.baeldung.collectors;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static java.util.stream.Collectors.maxBy;
|
||||
import static java.util.stream.Collectors.minBy;
|
||||
import static java.util.stream.Collectors.teeing;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* Unit tests for collectors additions in Java 12.
|
||||
*/
|
||||
public class CollectorsUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenTeeing_ItShouldCombineTheResultsAsExpected() {
|
||||
List<Integer> numbers = Arrays.asList(42, 4, 2, 24);
|
||||
Range range = numbers.stream()
|
||||
.collect(teeing(minBy(Integer::compareTo), maxBy(Integer::compareTo), (min, max) -> new Range(min.orElse(null), max.orElse(null))));
|
||||
|
||||
assertThat(range).isEqualTo(new Range(2, 42));
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents a closed range of numbers between {@link #min} and
|
||||
* {@link #max}, both inclusive.
|
||||
*/
|
||||
private static class Range {
|
||||
|
||||
private final Integer min;
|
||||
|
||||
private final Integer max;
|
||||
|
||||
Range(Integer min, Integer max) {
|
||||
this.min = min;
|
||||
this.max = max;
|
||||
}
|
||||
|
||||
Integer getMin() {
|
||||
return min;
|
||||
}
|
||||
|
||||
Integer getMax() {
|
||||
return max;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o)
|
||||
return true;
|
||||
if (o == null || getClass() != o.getClass())
|
||||
return false;
|
||||
Range range = (Range) o;
|
||||
return Objects.equals(getMin(), range.getMin()) && Objects.equals(getMax(), range.getMax());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(getMin(), getMax());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Range{" + "min=" + min + ", max=" + max + '}';
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
package com.baeldung.switchExpression;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class SwitchUnitTest {
|
||||
|
||||
@Test
|
||||
public void switchJava12(){
|
||||
|
||||
var month = Month.AUG;
|
||||
|
||||
var value = switch(month){
|
||||
case JAN,JUN, JUL -> 3;
|
||||
case FEB,SEP, OCT, NOV, DEC -> 1;
|
||||
case MAR,MAY, APR, AUG -> 2;
|
||||
};
|
||||
|
||||
Assert.assertEquals(value, 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void switchLocalVariable(){
|
||||
var month = Month.AUG;
|
||||
int i = switch (month){
|
||||
case JAN,JUN, JUL -> 3;
|
||||
case FEB,SEP, OCT, NOV, DEC -> 1;
|
||||
case MAR,MAY, APR, AUG -> {
|
||||
int j = month.toString().length() * 4;
|
||||
break j;
|
||||
}
|
||||
};
|
||||
Assert.assertEquals(12, i);
|
||||
}
|
||||
|
||||
enum Month {JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC}
|
||||
}
|
|
@ -0,0 +1,6 @@
|
|||
=========
|
||||
|
||||
## Core Java 8 Cookbooks and Examples (part 2)
|
||||
|
||||
### Relevant Articles:
|
||||
- [Anonymous Classes in Java](http://www.baeldung.com/)
|
|
@ -0,0 +1,43 @@
|
|||
<?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>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>core-java-8-2</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-8-2</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
</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}</source>
|
||||
<target>${maven.compiler.target}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
|
||||
</build>
|
||||
</project>
|
|
@ -3,7 +3,7 @@
|
|||
## Core Java 8 Cookbooks and Examples
|
||||
|
||||
### Relevant Articles:
|
||||
- [Java 8 Collectors](http://www.baeldung.com/java-8-collectors)
|
||||
- [Guide to Java 8’s Collectors](http://www.baeldung.com/java-8-collectors)
|
||||
- [Functional Interfaces in Java 8](http://www.baeldung.com/java-8-functional-interfaces)
|
||||
- [Java 8 – Powerful Comparison with Lambdas](http://www.baeldung.com/java-8-sort-lambda)
|
||||
- [New Features in Java 8](http://www.baeldung.com/java-8-new-features)
|
||||
|
|
|
@ -1,12 +0,0 @@
|
|||
package com.baeldung;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
|
||||
public interface Adder {
|
||||
|
||||
String addWithFunction(Function<String, String> f);
|
||||
|
||||
void addWithConsumer(Consumer<Integer> f);
|
||||
|
||||
}
|
|
@ -1,18 +0,0 @@
|
|||
package com.baeldung;
|
||||
|
||||
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
|
||||
public class AdderImpl implements Adder {
|
||||
|
||||
@Override
|
||||
public String addWithFunction(final Function<String, String> f) {
|
||||
return f.apply("Something ");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addWithConsumer(final Consumer<Integer> f) {
|
||||
}
|
||||
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung;
|
||||
package com.baeldung.java8.lambda.tips;
|
||||
|
||||
|
||||
@FunctionalInterface
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung;
|
||||
package com.baeldung.java8.lambda.tips;
|
||||
|
||||
|
||||
@FunctionalInterface
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung;
|
||||
package com.baeldung.java8.lambda.tips;
|
||||
|
||||
|
||||
@FunctionalInterface
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung;
|
||||
package com.baeldung.java8.lambda.tips;
|
||||
|
||||
|
||||
@FunctionalInterface
|
|
@ -0,0 +1,12 @@
|
|||
package com.baeldung.java8.lambda.tips;
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public interface Processor {
|
||||
|
||||
String processWithCallable(Callable<String> c) throws Exception;
|
||||
|
||||
String processWithSupplier(Supplier<String> s);
|
||||
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
package com.baeldung.java8.lambda.tips;
|
||||
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public class ProcessorImpl implements Processor {
|
||||
|
||||
@Override
|
||||
public String processWithCallable(Callable<String> c) throws Exception {
|
||||
return c.call();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String processWithSupplier(Supplier<String> s) {
|
||||
return s.get();
|
||||
}
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung;
|
||||
package com.baeldung.java8.lambda.tips;
|
||||
|
||||
|
||||
import java.util.function.Function;
|
|
@ -124,11 +124,44 @@ public class Java8SortUnitTest {
|
|||
|
||||
@Test
|
||||
public final void givenStreamCustomOrdering_whenSortingEntitiesByName_thenCorrectlySorted() {
|
||||
|
||||
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
|
||||
final Comparator<Human> nameComparator = (h1, h2) -> h1.getName().compareTo(h2.getName());
|
||||
|
||||
final List<Human> sortedHumans = humans.stream().sorted(nameComparator).collect(Collectors.toList());
|
||||
Assert.assertThat(sortedHumans.get(0), equalTo(new Human("Jack", 12)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenStreamComparatorOrdering_whenSortingEntitiesByName_thenCorrectlySorted() {
|
||||
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
|
||||
|
||||
final List<Human> sortedHumans = humans.stream().sorted(Comparator.comparing(Human::getName)).collect(Collectors.toList());
|
||||
Assert.assertThat(sortedHumans.get(0), equalTo(new Human("Jack", 12)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenStreamNaturalOrdering_whenSortingEntitiesByNameReversed_thenCorrectlySorted() {
|
||||
final List<String> letters = Lists.newArrayList("B", "A", "C");
|
||||
|
||||
final List<String> reverseSortedLetters = letters.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
|
||||
Assert.assertThat(reverseSortedLetters.get(0), equalTo("C"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenStreamCustomOrdering_whenSortingEntitiesByNameReversed_thenCorrectlySorted() {
|
||||
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
|
||||
final Comparator<Human> reverseNameComparator = (h1, h2) -> h2.getName().compareTo(h1.getName());
|
||||
|
||||
final List<Human> reverseSortedHumans = humans.stream().sorted(reverseNameComparator).collect(Collectors.toList());
|
||||
Assert.assertThat(reverseSortedHumans.get(0), equalTo(new Human("Sarah", 10)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenStreamComparatorOrdering_whenSortingEntitiesByNameReversed_thenCorrectlySorted() {
|
||||
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
|
||||
|
||||
final List<Human> reverseSortedHumans = humans.stream().sorted(Comparator.comparing(Human::getName, Comparator.reverseOrder())).collect(Collectors.toList());
|
||||
Assert.assertThat(reverseSortedHumans.get(0), equalTo(new Human("Sarah", 10)));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
package com.baeldung.java8;
|
||||
package com.baeldung.java8.lambda.tips;
|
||||
|
||||
import com.baeldung.Foo;
|
||||
import com.baeldung.FooExtended;
|
||||
import com.baeldung.UseFoo;
|
||||
import com.baeldung.java8.lambda.tips.Foo;
|
||||
import com.baeldung.java8.lambda.tips.FooExtended;
|
||||
import com.baeldung.java8.lambda.tips.UseFoo;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
|
@ -27,34 +27,35 @@ public class OptionalUnitTest {
|
|||
@Test
|
||||
public void givenNonNull_whenCreatesNonNullable_thenCorrect() {
|
||||
String name = "baeldung";
|
||||
Optional.of(name);
|
||||
Optional<String> opt = Optional.of(name);
|
||||
assertTrue(opt.isPresent());
|
||||
}
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void givenNull_whenThrowsErrorOnCreate_thenCorrect() {
|
||||
String name = null;
|
||||
Optional<String> opt = Optional.of(name);
|
||||
Optional.of(name);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNonNull_whenCreatesOptional_thenCorrect() {
|
||||
String name = "baeldung";
|
||||
Optional<String> opt = Optional.of(name);
|
||||
assertEquals("Optional[baeldung]", opt.toString());
|
||||
assertTrue(opt.isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNonNull_whenCreatesNullable_thenCorrect() {
|
||||
String name = "baeldung";
|
||||
Optional<String> opt = Optional.ofNullable(name);
|
||||
assertEquals("Optional[baeldung]", opt.toString());
|
||||
assertTrue(opt.isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNull_whenCreatesNullable_thenCorrect() {
|
||||
String name = null;
|
||||
Optional<String> opt = Optional.ofNullable(name);
|
||||
assertEquals("Optional.empty", opt.toString());
|
||||
assertFalse(opt.isPresent());
|
||||
}
|
||||
// Checking Value With isPresent()
|
||||
|
||||
|
|
|
@ -29,4 +29,11 @@ public class CalculatorUnitTest {
|
|||
int result = calculator.calculate(new AddCommand(3, 7));
|
||||
assertEquals(10, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCalculateUsingFactory_thenReturnCorrectResult() {
|
||||
Calculator calculator = new Calculator();
|
||||
int result = calculator.calculateUsingFactory(3, 4, "add");
|
||||
assertEquals(7, result);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -5,27 +5,21 @@
|
|||
[Java 9 New Features](http://www.baeldung.com/new-java-9)
|
||||
|
||||
### Relevant Articles:
|
||||
- [Java 9 Stream API Improvements](http://www.baeldung.com/java-9-stream-api)
|
||||
- [Java 9 Convenience Factory Methods for Collections](http://www.baeldung.com/java-9-collections-factory-methods)
|
||||
|
||||
- [Java 9 New Features](https://www.baeldung.com/new-java-9)
|
||||
- [New Stream Collectors in Java 9](http://www.baeldung.com/java9-stream-collectors)
|
||||
- [Java 9 CompletableFuture API Improvements](http://www.baeldung.com/java-9-completablefuture)
|
||||
- [Java 9 Process API Improvements](http://www.baeldung.com/java-9-process-api)
|
||||
- [Introduction to Java 9 StackWalking API](http://www.baeldung.com/java-9-stackwalking-api)
|
||||
- [Introduction to Project Jigsaw](http://www.baeldung.com/project-jigsaw-java-modularity)
|
||||
- [Java 9 Optional API Additions](http://www.baeldung.com/java-9-optional)
|
||||
- [Java 9 Reactive Streams](http://www.baeldung.com/java-9-reactive-streams)
|
||||
- [Java 9 java.util.Objects Additions](http://www.baeldung.com/java-9-objects-new)
|
||||
- [Java 9 Variable Handles Demistyfied](http://www.baeldung.com/java-variable-handles)
|
||||
- [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)
|
||||
- [Method Handles in Java](http://www.baeldung.com/java-method-handles)
|
||||
- [Introduction to Chronicle Queue](http://www.baeldung.com/java-chronicle-queue)
|
||||
- [A Guide to Java 9 Modularity](http://www.baeldung.com/java-9-modularity)
|
||||
- [Optional orElse Optional](http://www.baeldung.com/java-optional-or-else-optional)
|
||||
- [Java 9 java.lang.Module API](http://www.baeldung.com/java-9-module-api)
|
||||
- [Iterate Through a Range of Dates in Java](https://www.baeldung.com/java-iterate-date-range)
|
||||
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
|
||||
- [Java 9 Platform Logging API](https://www.baeldung.com/java-9-logging-api)
|
||||
- [Guide to java.lang.Process API](https://www.baeldung.com/java-process-api)
|
||||
- [Immutable Set in Java](https://www.baeldung.com/java-immutable-set)
|
||||
- [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)
|
||||
- [Java 9 Process API Improvements](https://www.baeldung.com/java-9-process-api)
|
||||
- [Guide to java.lang.Process API](https://www.baeldung.com/java-process-api)
|
||||
|
||||
|
||||
|
|
|
@ -0,0 +1,34 @@
|
|||
package com.baeldung.array;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
|
||||
public class AddElementToEndOfArray {
|
||||
|
||||
public Integer[] addElementUsingArraysCopyOf(Integer[] srcArray, int elementToAdd) {
|
||||
Integer[] destArray = Arrays.copyOf(srcArray, srcArray.length + 1);
|
||||
|
||||
destArray[destArray.length - 1] = elementToAdd;
|
||||
return destArray;
|
||||
}
|
||||
|
||||
public Integer[] addElementUsingArrayList(Integer[] srcArray, int elementToAdd) {
|
||||
Integer[] destArray = new Integer[srcArray.length + 1];
|
||||
|
||||
ArrayList<Integer> arrayList = new ArrayList<>(Arrays.asList(srcArray));
|
||||
arrayList.add(elementToAdd);
|
||||
|
||||
return arrayList.toArray(destArray);
|
||||
}
|
||||
|
||||
public Integer[] addElementUsingSystemArrayCopy(Integer[] srcArray, int elementToAdd) {
|
||||
Integer[] destArray = new Integer[srcArray.length + 1];
|
||||
|
||||
System.arraycopy(srcArray, 0, destArray, 0, srcArray.length);
|
||||
|
||||
destArray[destArray.length - 1] = elementToAdd;
|
||||
|
||||
return destArray;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,49 @@
|
|||
package com.baeldung.array;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
|
||||
public class AddElementToEndOfArrayUnitTest {
|
||||
|
||||
AddElementToEndOfArray addElementToEndOfArray;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
addElementToEndOfArray = new AddElementToEndOfArray();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSourceArrayAndElement_whenAddElementUsingArraysCopyIsInvoked_thenNewElementMustBeAdded() {
|
||||
Integer[] sourceArray = {1, 2, 3, 4};
|
||||
int elementToAdd = 5;
|
||||
|
||||
Integer[] destArray = addElementToEndOfArray.addElementUsingArraysCopyOf(sourceArray, elementToAdd);
|
||||
|
||||
Integer[] expectedArray = {1, 2, 3, 4, 5};
|
||||
assertArrayEquals(expectedArray, destArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSourceArrayAndElement_whenAddElementUsingArrayListIsInvoked_thenNewElementMustBeAdded() {
|
||||
Integer[] sourceArray = {1, 2, 3, 4};
|
||||
int elementToAdd = 5;
|
||||
|
||||
Integer[] destArray = addElementToEndOfArray.addElementUsingArrayList(sourceArray, elementToAdd);
|
||||
|
||||
Integer[] expectedArray = {1, 2, 3, 4, 5};
|
||||
assertArrayEquals(expectedArray, destArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSourceArrayAndElement_whenAddElementUsingSystemArrayCopyIsInvoked_thenNewElementMustBeAdded() {
|
||||
Integer[] sourceArray = {1, 2, 3, 4};
|
||||
int elementToAdd = 5;
|
||||
|
||||
Integer[] destArray = addElementToEndOfArray.addElementUsingSystemArrayCopy(sourceArray, elementToAdd);
|
||||
|
||||
Integer[] expectedArray = {1, 2, 3, 4, 5};
|
||||
assertArrayEquals(expectedArray, destArray);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
=========
|
||||
|
||||
## Core Java Sets Cookbooks and Examples
|
||||
|
||||
### Relevant Articles:
|
||||
- [Set Operations in Java](http://www.baeldung.com/set-operations-in-java)
|
||||
- [HashSet and TreeSet Comparison](http://www.baeldung.com/java-hashset-vs-treeset)
|
||||
- [A Guide to HashSet in Java](http://www.baeldung.com/java-hashset)
|
||||
- [A Guide to TreeSet in Java](http://www.baeldung.com/java-tree-set)
|
||||
- [Initializing HashSet at the Time of Construction](http://www.baeldung.com/java-initialize-hashset)
|
||||
- [Guide to EnumSet](https://www.baeldung.com/java-enumset)
|
|
@ -0,0 +1,33 @@
|
|||
<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-set</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-collections-set</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>${commons-collections4.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<commons-collections4.version>4.3</commons-collections4.version>
|
||||
<guava.version>27.1-jre</guava.version>
|
||||
</properties>
|
||||
</project>
|
|
@ -0,0 +1,93 @@
|
|||
package com.baeldung.set;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.apache.commons.collections4.SetUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.collect.Sets;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class SetOperationsUnitTest {
|
||||
|
||||
private Set<Integer> setA = setOf(1,2,3,4);
|
||||
private Set<Integer> setB = setOf(2,4,6,8);
|
||||
|
||||
private static Set<Integer> setOf(Integer... values) {
|
||||
return new HashSet<Integer>(Arrays.asList(values));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoSets_WhenWeRetainAll_ThenWeIntersectThem() {
|
||||
Set<Integer> intersectSet = new HashSet<>(setA);
|
||||
intersectSet.retainAll(setB);
|
||||
assertEquals(setOf(2,4), intersectSet);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoSets_WhenWeAddAll_ThenWeUnionThem() {
|
||||
Set<Integer> unionSet = new HashSet<>(setA);
|
||||
unionSet.addAll(setB);
|
||||
assertEquals(setOf(1,2,3,4,6,8), unionSet);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoSets_WhenRemoveAll_ThenWeGetTheDifference() {
|
||||
Set<Integer> differenceSet = new HashSet<>(setA);
|
||||
differenceSet.removeAll(setB);
|
||||
assertEquals(setOf(1,3), differenceSet);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoStreams_WhenWeFilterThem_ThenWeCanGetTheIntersect() {
|
||||
Set<Integer> intersectSet = setA.stream()
|
||||
.filter(setB::contains)
|
||||
.collect(Collectors.toSet());
|
||||
assertEquals(setOf(2,4), intersectSet);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoStreams_WhenWeConcatThem_ThenWeGetTheUnion() {
|
||||
Set<Integer> unionSet = Stream.concat(setA.stream(), setB.stream())
|
||||
.collect(Collectors.toSet());
|
||||
assertEquals(setOf(1,2,3,4,6,8), unionSet);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoStreams_WhenWeFilterThem_ThenWeCanGetTheDifference() {
|
||||
Set<Integer> differenceSet = setA.stream()
|
||||
.filter(val -> !setB.contains(val))
|
||||
.collect(Collectors.toSet());
|
||||
assertEquals(setOf(1,3), differenceSet);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoSets_WhenWeUseApacheCommonsIntersect_ThenWeGetTheIntersect() {
|
||||
Set<Integer> intersectSet = SetUtils.intersection(setA, setB);
|
||||
assertEquals(setOf(2,4), intersectSet);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoSets_WhenWeUseApacheCommonsUnion_ThenWeGetTheUnion() {
|
||||
Set<Integer> unionSet = SetUtils.union(setA, setB);
|
||||
assertEquals(setOf(1,2,3,4,6,8), unionSet);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenTwoSets_WhenWeUseGuavaIntersect_ThenWeGetTheIntersect() {
|
||||
Set<Integer> intersectSet = Sets.intersection(setA, setB);
|
||||
assertEquals(setOf(2,4), intersectSet);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoSets_WhenWeUseGuavaUnion_ThenWeGetTheUnion() {
|
||||
Set<Integer> unionSet = Sets.union(setA, setB);
|
||||
assertEquals(setOf(1,2,3,4,6,8), unionSet);
|
||||
}
|
||||
}
|
|
@ -3,15 +3,11 @@
|
|||
## Core Java Collections Cookbooks and Examples
|
||||
|
||||
### Relevant Articles:
|
||||
- [Java - Combine Multiple Collections](http://www.baeldung.com/java-combine-multiple-collections)
|
||||
- [HashSet and TreeSet Comparison](http://www.baeldung.com/java-hashset-vs-treeset)
|
||||
- [Java – Combine Multiple Collections](http://www.baeldung.com/java-combine-multiple-collections)
|
||||
- [Collect a Java Stream to an Immutable Collection](http://www.baeldung.com/java-stream-immutable-collection)
|
||||
- [Introduction to the Java ArrayDeque](http://www.baeldung.com/java-array-deque)
|
||||
- [A Guide to HashSet in Java](http://www.baeldung.com/java-hashset)
|
||||
- [A Guide to TreeSet in Java](http://www.baeldung.com/java-tree-set)
|
||||
- [Getting the Size of an Iterable in Java](http://www.baeldung.com/java-iterable-size)
|
||||
- [How to Filter a Collection in Java](http://www.baeldung.com/java-collection-filtering)
|
||||
- [Initializing HashSet at the Time of Construction](http://www.baeldung.com/java-initialize-hashset)
|
||||
- [Removing the First Element of an Array](https://www.baeldung.com/java-array-remove-first-element)
|
||||
- [Fail-Safe Iterator vs Fail-Fast Iterator](http://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator)
|
||||
- [Shuffling Collections In Java](http://www.baeldung.com/java-shuffle-collection)
|
||||
|
@ -23,7 +19,6 @@
|
|||
- [Time Complexity of Java Collections](https://www.baeldung.com/java-collections-complexity)
|
||||
- [Operating on and Removing an Item from Stream](https://www.baeldung.com/java-use-remove-item-stream)
|
||||
- [An Introduction to Synchronized Java Collections](https://www.baeldung.com/java-synchronized-collections)
|
||||
- [Guide to EnumSet](https://www.baeldung.com/java-enumset)
|
||||
- [Removing Elements from Java Collections](https://www.baeldung.com/java-collection-remove-elements)
|
||||
- [Combining Different Types of Collections in Java](https://www.baeldung.com/java-combine-collections)
|
||||
- [Sorting in Java](http://www.baeldung.com/java-sorting)
|
||||
|
@ -33,3 +28,4 @@
|
|||
- [Differences Between HashMap and Hashtable](https://www.baeldung.com/hashmap-hashtable-differences)
|
||||
- [Java ArrayList vs Vector](https://www.baeldung.com/java-arraylist-vs-vector)
|
||||
- [Defining a Char Stack in Java](https://www.baeldung.com/java-char-stack)
|
||||
- [Time Comparison of Arrays.sort(Object[]) and Arrays.sort(int[])](https://www.baeldung.com/arrays-sortobject-vs-sortint)
|
||||
|
|
|
@ -12,7 +12,7 @@
|
|||
- [Guide to the Java Phaser](http://www.baeldung.com/java-phaser)
|
||||
- [An Introduction to Atomic Variables in Java](http://www.baeldung.com/java-atomic-variables)
|
||||
- [CyclicBarrier in Java](http://www.baeldung.com/java-cyclic-barrier)
|
||||
- [Guide to Volatile Keyword in Java](http://www.baeldung.com/java-volatile)
|
||||
- [Guide to the Volatile Keyword in Java](http://www.baeldung.com/java-volatile)
|
||||
- [Semaphores in Java](http://www.baeldung.com/java-semaphore)
|
||||
- [Daemon Threads in Java](http://www.baeldung.com/java-daemon-thread)
|
||||
- [Priority-based Job Scheduling in Java](http://www.baeldung.com/java-priority-job-schedule)
|
||||
|
@ -20,5 +20,6 @@
|
|||
- [Print Even and Odd Numbers Using 2 Threads](https://www.baeldung.com/java-even-odd-numbers-with-2-threads)
|
||||
- [Java CyclicBarrier vs CountDownLatch](https://www.baeldung.com/java-cyclicbarrier-countdownlatch)
|
||||
- [Guide to the Fork/Join Framework in Java](http://www.baeldung.com/java-fork-join)
|
||||
- [A Guide to ThreadLocalRandom in Java](http://www.baeldung.com/java-thread-local-random)
|
||||
- [The Thread.join() Method in Java](http://www.baeldung.com/java-thread-join)
|
||||
- [Guide to ThreadLocalRandom in Java](http://www.baeldung.com/java-thread-local-random)
|
||||
- [The Thread.join() Method in Java](http://www.baeldung.com/java-thread-join)
|
||||
- [Passing Parameters to Java Threads](https://www.baeldung.com/java-thread-parameters)
|
||||
|
|
|
@ -7,12 +7,13 @@
|
|||
- [A Guide to the Java ExecutorService](http://www.baeldung.com/java-executor-service-tutorial)
|
||||
- [Guide to java.util.concurrent.Future](http://www.baeldung.com/java-future)
|
||||
- [Difference Between Wait and Sleep in Java](http://www.baeldung.com/java-wait-and-sleep)
|
||||
- [Guide to Synchronized Keyword in Java](http://www.baeldung.com/java-synchronized)
|
||||
- [Guide to the Synchronized Keyword in Java](http://www.baeldung.com/java-synchronized)
|
||||
- [Overview of the java.util.concurrent](http://www.baeldung.com/java-util-concurrent)
|
||||
- [Implementing a Runnable vs Extending a Thread](http://www.baeldung.com/java-runnable-vs-extending-thread)
|
||||
- [How to Kill a Java Thread](http://www.baeldung.com/java-thread-stop)
|
||||
- [ExecutorService - Waiting for Threads to Finish](http://www.baeldung.com/java-executor-wait-for-threads)
|
||||
- [ExecutorService – Waiting for Threads to Finish](http://www.baeldung.com/java-executor-wait-for-threads)
|
||||
- [wait and notify() Methods in Java](http://www.baeldung.com/java-wait-notify)
|
||||
- [Life Cycle of a Thread in Java](http://www.baeldung.com/java-thread-lifecycle)
|
||||
- [Runnable vs. Callable in Java](http://www.baeldung.com/java-runnable-callable)
|
||||
- [What is Thread-Safety and How to Achieve it](https://www.baeldung.com/java-thread-safety)
|
||||
- [What is Thread-Safety and How to Achieve it?](https://www.baeldung.com/java-thread-safety)
|
||||
- [How to Start a Thread in Java](https://www.baeldung.com/java-start-thread)
|
||||
|
|
|
@ -6,7 +6,7 @@
|
|||
- [How to Read a Large File Efficiently with Java](http://www.baeldung.com/java-read-lines-large-file)
|
||||
- [Java InputStream to String](http://www.baeldung.com/convert-input-stream-to-string)
|
||||
- [Java – Write to File](http://www.baeldung.com/java-write-to-file)
|
||||
- [Java - Convert File to InputStream](http://www.baeldung.com/convert-file-to-input-stream)
|
||||
- [Java – Convert File to InputStream](http://www.baeldung.com/convert-file-to-input-stream)
|
||||
- [Java Scanner](http://www.baeldung.com/java-scanner)
|
||||
- [Java – Byte Array to Writer](http://www.baeldung.com/java-convert-byte-array-to-writer)
|
||||
- [Java – Directory Size](http://www.baeldung.com/java-folder-size)
|
||||
|
@ -14,7 +14,7 @@
|
|||
- [File Size in Java](http://www.baeldung.com/java-file-size)
|
||||
- [Comparing getPath(), getAbsolutePath(), and getCanonicalPath() in Java](http://www.baeldung.com/java-path)
|
||||
- [Using Java MappedByteBuffer](http://www.baeldung.com/java-mapped-byte-buffer)
|
||||
- [Copy a File with Java](http://www.baeldung.com/java-copy-file)
|
||||
- [How to Copy a File with Java](http://www.baeldung.com/java-copy-file)
|
||||
- [Java – Append Data to a File](http://www.baeldung.com/java-append-to-file)
|
||||
- [FileNotFoundException in Java](http://www.baeldung.com/java-filenotfound-exception)
|
||||
- [How to Read a File in Java](http://www.baeldung.com/reading-file-in-java)
|
||||
|
@ -30,7 +30,6 @@
|
|||
- [Download a File From an URL in Java](http://www.baeldung.com/java-download-file)
|
||||
- [Create a Symbolic Link with Java](http://www.baeldung.com/java-symlink)
|
||||
- [Quick Use of FilenameFilter](http://www.baeldung.com/java-filename-filter)
|
||||
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
|
||||
- [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)
|
||||
|
@ -40,3 +39,4 @@
|
|||
- [Create a Directory in Java](https://www.baeldung.com/java-create-directory)
|
||||
- [How to Write to a CSV File in Java](https://www.baeldung.com/java-csv)
|
||||
- [List Files in a Directory in Java](https://www.baeldung.com/java-list-directory-files)
|
||||
- [Java InputStream to Byte Array and ByteBuffer](https://www.baeldung.com/convert-input-stream-to-array-of-bytes)
|
||||
|
|
|
@ -0,0 +1,165 @@
|
|||
package com.baeldung.filechannel;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.RandomAccessFile;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.MappedByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.channels.FileLock;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class FileChannelUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenFile_whenReadWithFileChannelUsingRandomAccessFile_thenCorrect() throws IOException {
|
||||
|
||||
try (RandomAccessFile reader = new RandomAccessFile("src/test/resources/test_read.in", "r");
|
||||
FileChannel channel = reader.getChannel();
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();) {
|
||||
|
||||
int bufferSize = 1024;
|
||||
if (bufferSize > channel.size()) {
|
||||
bufferSize = (int) channel.size();
|
||||
}
|
||||
ByteBuffer buff = ByteBuffer.allocate(bufferSize);
|
||||
|
||||
while (channel.read(buff) > 0) {
|
||||
out.write(buff.array(), 0, buff.position());
|
||||
buff.clear();
|
||||
}
|
||||
|
||||
String fileContent = new String(out.toByteArray(), StandardCharsets.UTF_8);
|
||||
|
||||
assertEquals("Hello world", fileContent);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFile_whenReadWithFileChannelUsingFileInputStream_thenCorrect() throws IOException {
|
||||
|
||||
try (ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
FileInputStream fin = new FileInputStream("src/test/resources/test_read.in");
|
||||
FileChannel channel = fin.getChannel();) {
|
||||
|
||||
int bufferSize = 1024;
|
||||
if (bufferSize > channel.size()) {
|
||||
bufferSize = (int) channel.size();
|
||||
}
|
||||
ByteBuffer buff = ByteBuffer.allocate(bufferSize);
|
||||
|
||||
while (channel.read(buff) > 0) {
|
||||
out.write(buff.array(), 0, buff.position());
|
||||
buff.clear();
|
||||
}
|
||||
String fileContent = new String(out.toByteArray(), StandardCharsets.UTF_8);
|
||||
|
||||
assertEquals("Hello world", fileContent);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFile_whenReadAFileSectionIntoMemoryWithFileChannel_thenCorrect() throws IOException {
|
||||
|
||||
try (RandomAccessFile reader = new RandomAccessFile("src/test/resources/test_read.in", "r");
|
||||
FileChannel channel = reader.getChannel();
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();) {
|
||||
|
||||
MappedByteBuffer buff = channel.map(FileChannel.MapMode.READ_ONLY, 6, 5);
|
||||
|
||||
if (buff.hasRemaining()) {
|
||||
byte[] data = new byte[buff.remaining()];
|
||||
buff.get(data);
|
||||
assertEquals("world", new String(data, StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenWriteWithFileChannelUsingRandomAccessFile_thenCorrect() throws IOException {
|
||||
String file = "src/test/resources/test_write_using_filechannel.txt";
|
||||
try (RandomAccessFile writer = new RandomAccessFile(file, "rw");
|
||||
FileChannel channel = writer.getChannel();) {
|
||||
ByteBuffer buff = ByteBuffer.wrap("Hello world".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
channel.write(buff);
|
||||
|
||||
// now we verify whether the file was written correctly
|
||||
RandomAccessFile reader = new RandomAccessFile(file, "r");
|
||||
assertEquals("Hello world", reader.readLine());
|
||||
reader.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFile_whenWriteAFileUsingLockAFileSectionWithFileChannel_thenCorrect() throws IOException {
|
||||
try (RandomAccessFile reader = new RandomAccessFile("src/test/resources/test_read.in", "rw");
|
||||
FileChannel channel = reader.getChannel();
|
||||
FileLock fileLock = channel.tryLock(6, 5, Boolean.FALSE);) {
|
||||
|
||||
assertNotNull(fileLock);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFile_whenReadWithFileChannelGetPosition_thenCorrect() throws IOException {
|
||||
|
||||
try (ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
RandomAccessFile reader = new RandomAccessFile("src/test/resources/test_read.in", "r");
|
||||
FileChannel channel = reader.getChannel();) {
|
||||
|
||||
int bufferSize = 1024;
|
||||
if (bufferSize > channel.size()) {
|
||||
bufferSize = (int) channel.size();
|
||||
}
|
||||
ByteBuffer buff = ByteBuffer.allocate(bufferSize);
|
||||
|
||||
while (channel.read(buff) > 0) {
|
||||
out.write(buff.array(), 0, buff.position());
|
||||
buff.clear();
|
||||
}
|
||||
|
||||
// the original file is 11 bytes long, so that's where the position pointer should be
|
||||
assertEquals(11, channel.position());
|
||||
|
||||
channel.position(4);
|
||||
assertEquals(4, channel.position());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetFileSize_thenCorrect() throws IOException {
|
||||
|
||||
try (RandomAccessFile reader = new RandomAccessFile("src/test/resources/test_read.in", "r");
|
||||
FileChannel channel = reader.getChannel();) {
|
||||
|
||||
// the original file is 11 bytes long, so that's where the position pointer should be
|
||||
assertEquals(11, channel.size());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenTruncateFile_thenCorrect() throws IOException {
|
||||
String input = "this is a test input";
|
||||
|
||||
FileOutputStream fout = new FileOutputStream("src/test/resources/test_truncate.txt");
|
||||
FileChannel channel = fout.getChannel();
|
||||
|
||||
ByteBuffer buff = ByteBuffer.wrap(input.getBytes());
|
||||
channel.write(buff);
|
||||
buff.flip();
|
||||
|
||||
channel = channel.truncate(5);
|
||||
assertEquals(5, channel.size());
|
||||
|
||||
fout.close();
|
||||
channel.close();
|
||||
}
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
this
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue