Merge branch 'master' into BAEL-3521
This commit is contained in:
commit
de9d0f06f2
@ -7,8 +7,6 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
|
||||
|
||||
- [Validating Input With Finite Automata in Java](https://www.baeldung.com/java-finite-automata)
|
||||
- [Example of Hill Climbing Algorithm](https://www.baeldung.com/java-hill-climbing-algorithm)
|
||||
- [Monte Carlo Tree Search for Tic-Tac-Toe Game](https://www.baeldung.com/java-monte-carlo-tree-search)
|
||||
- [Binary Search Algorithm in Java](https://www.baeldung.com/java-binary-search)
|
||||
- [Introduction to Minimax Algorithm](https://www.baeldung.com/java-minimax-algorithm)
|
||||
- [How to Calculate Levenshtein Distance in Java?](https://www.baeldung.com/java-levenshtein-distance)
|
||||
- [How to Find the Kth Largest Element in Java](https://www.baeldung.com/java-kth-largest-element)
|
||||
|
@ -14,8 +14,6 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
|
||||
- [A Guide to the Folding Technique in Java](https://www.baeldung.com/folding-hashing-technique)
|
||||
- [Creating a Triangle with for Loops in Java](https://www.baeldung.com/java-print-triangle)
|
||||
- [Efficient Word Frequency Calculator in Java](https://www.baeldung.com/java-word-frequency)
|
||||
- [Interpolation Search in Java](https://www.baeldung.com/java-interpolation-search)
|
||||
- [The K-Means Clustering Algorithm in Java](https://www.baeldung.com/java-k-means-clustering-algorithm)
|
||||
- [Creating a Custom Annotation in Java](https://www.baeldung.com/java-custom-annotation)
|
||||
- [Breadth-First Search Algorithm in Java](https://www.baeldung.com/java-breadth-first-search)
|
||||
- More articles: [[<-- prev]](/algorithms-miscellaneous-2) [[next -->]](/algorithms-miscellaneous-4)
|
||||
|
@ -5,10 +5,10 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
|
||||
### Relevant articles:
|
||||
|
||||
- [Multi-Swarm Optimization Algorithm in Java](https://www.baeldung.com/java-multi-swarm-algorithm)
|
||||
- [String Search Algorithms for Large Texts](https://www.baeldung.com/java-full-text-search-algorithms)
|
||||
- [Check If a String Contains All The Letters of The Alphabet](https://www.baeldung.com/java-string-contains-all-letters)
|
||||
- [Find the Middle Element of a Linked List](https://www.baeldung.com/java-linked-list-middle-element)
|
||||
- [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)
|
||||
- [Permutations of an Array in Java](https://www.baeldung.com/java-array-permutations)
|
||||
- [Find the Smallest Missing Integer in an Array](https://www.baeldung.com/java-smallest-missing-integer-in-array)
|
||||
- More articles: [[<-- prev]](/algorithms-miscellaneous-3) [[next -->]](/algorithms-miscellaneous-5)
|
||||
|
@ -1,25 +0,0 @@
|
||||
package com.baeldung.algorithms;
|
||||
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.algorithms.string.search.StringSearchAlgorithms;
|
||||
|
||||
public class StringSearchAlgorithmsUnitTest {
|
||||
|
||||
|
||||
@Test
|
||||
public void testStringSearchAlgorithms(){
|
||||
String text = "This is some nice text.";
|
||||
String pattern = "some";
|
||||
|
||||
int realPosition = text.indexOf(pattern);
|
||||
Assert.assertTrue(realPosition == StringSearchAlgorithms.simpleTextSearch(pattern.toCharArray(), text.toCharArray()));
|
||||
Assert.assertTrue(realPosition == StringSearchAlgorithms.RabinKarpMethod(pattern.toCharArray(), text.toCharArray()));
|
||||
Assert.assertTrue(realPosition == StringSearchAlgorithms.KnuthMorrisPrattSearch(pattern.toCharArray(), text.toCharArray()));
|
||||
Assert.assertTrue(realPosition == StringSearchAlgorithms.BoyerMooreHorspoolSimpleSearch(pattern.toCharArray(), text.toCharArray()));
|
||||
Assert.assertTrue(realPosition == StringSearchAlgorithms.BoyerMooreHorspoolSearch(pattern.toCharArray(), text.toCharArray()));
|
||||
}
|
||||
|
||||
}
|
@ -9,4 +9,5 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
|
||||
- [Reversing a Binary Tree in Java](https://www.baeldung.com/java-reversing-a-binary-tree)
|
||||
- [Find If Two Numbers Are Relatively Prime in Java](https://www.baeldung.com/java-two-relatively-prime-numbers)
|
||||
- [Knapsack Problem Implementation in Java](https://www.baeldung.com/java-knapsack)
|
||||
- [How to Determine if a Binary Tree is Balanced](https://www.baeldung.com/java-balanced-binary-tree)
|
||||
- More articles: [[<-- prev]](/../algorithms-miscellaneous-4)
|
||||
|
@ -17,6 +17,11 @@
|
||||
<artifactId>commons-codec</artifactId>
|
||||
<version>${commons-codec.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-math3</artifactId>
|
||||
<version>${commons-math3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
@ -28,6 +33,7 @@
|
||||
<artifactId>tradukisto</artifactId>
|
||||
<version>${tradukisto.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
@ -52,6 +58,7 @@
|
||||
<tradukisto.version>1.0.1</tradukisto.version>
|
||||
<org.assertj.core.version>3.9.0</org.assertj.core.version>
|
||||
<commons-codec.version>1.11</commons-codec.version>
|
||||
<commons-math3.version>3.6.1</commons-math3.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -0,0 +1,83 @@
|
||||
package com.baeldung.algorithms.caesarcipher;
|
||||
|
||||
import org.apache.commons.math3.stat.inference.ChiSquareTest;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class CaesarCipher {
|
||||
private static final char LETTER_A = 'a';
|
||||
private static final char LETTER_Z = 'z';
|
||||
private static final int ALPHABET_SIZE = LETTER_Z - LETTER_A + 1;
|
||||
private static final double[] ENGLISH_LETTERS_PROBABILITIES = {0.073, 0.009, 0.030, 0.044, 0.130, 0.028, 0.016, 0.035, 0.074, 0.002, 0.003, 0.035, 0.025, 0.078, 0.074, 0.027, 0.003, 0.077, 0.063, 0.093, 0.027, 0.013, 0.016, 0.005, 0.019, 0.001};
|
||||
|
||||
public String cipher(String message, int offset) {
|
||||
StringBuilder result = new StringBuilder();
|
||||
|
||||
for (char character : message.toCharArray()) {
|
||||
if (character != ' ') {
|
||||
int originalAlphabetPosition = character - LETTER_A;
|
||||
int newAlphabetPosition = (originalAlphabetPosition + offset) % ALPHABET_SIZE;
|
||||
char newCharacter = (char) (LETTER_A + newAlphabetPosition);
|
||||
result.append(newCharacter);
|
||||
} else {
|
||||
result.append(character);
|
||||
}
|
||||
}
|
||||
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
public String decipher(String message, int offset) {
|
||||
return cipher(message, ALPHABET_SIZE - (offset % ALPHABET_SIZE));
|
||||
}
|
||||
|
||||
public int breakCipher(String message) {
|
||||
return probableOffset(chiSquares(message));
|
||||
}
|
||||
|
||||
private double[] chiSquares(String message) {
|
||||
double[] expectedLettersFrequencies = expectedLettersFrequencies(message.length());
|
||||
|
||||
double[] chiSquares = new double[ALPHABET_SIZE];
|
||||
|
||||
for (int offset = 0; offset < chiSquares.length; offset++) {
|
||||
String decipheredMessage = decipher(message, offset);
|
||||
long[] lettersFrequencies = observedLettersFrequencies(decipheredMessage);
|
||||
double chiSquare = new ChiSquareTest().chiSquare(expectedLettersFrequencies, lettersFrequencies);
|
||||
chiSquares[offset] = chiSquare;
|
||||
}
|
||||
|
||||
return chiSquares;
|
||||
}
|
||||
|
||||
private long[] observedLettersFrequencies(String message) {
|
||||
return IntStream.rangeClosed(LETTER_A, LETTER_Z)
|
||||
.mapToLong(letter -> countLetter((char) letter, message))
|
||||
.toArray();
|
||||
}
|
||||
|
||||
private long countLetter(char letter, String message) {
|
||||
return message.chars()
|
||||
.filter(character -> character == letter)
|
||||
.count();
|
||||
}
|
||||
|
||||
private double[] expectedLettersFrequencies(int messageLength) {
|
||||
return Arrays.stream(ENGLISH_LETTERS_PROBABILITIES)
|
||||
.map(probability -> probability * messageLength)
|
||||
.toArray();
|
||||
}
|
||||
|
||||
private int probableOffset(double[] chiSquares) {
|
||||
int probableOffset = 0;
|
||||
for (int offset = 0; offset < chiSquares.length; offset++) {
|
||||
System.out.println(String.format("Chi-Square for offset %d: %.2f", offset, chiSquares[offset]));
|
||||
if (chiSquares[offset] < chiSquares[probableOffset]) {
|
||||
probableOffset = offset;
|
||||
}
|
||||
}
|
||||
|
||||
return probableOffset;
|
||||
}
|
||||
}
|
@ -0,0 +1,83 @@
|
||||
package com.baeldung.algorithms.caesarcipher;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class CaesarCipherUnitTest {
|
||||
private static final String SENTENCE = "he told me i could never teach a llama to drive";
|
||||
private static final String SENTENCE_SHIFTED_THREE = "kh wrog ph l frxog qhyhu whdfk d oodpd wr gulyh";
|
||||
private static final String SENTENCE_SHIFTED_TEN = "ro dyvn wo s myevn xofob dokmr k vvkwk dy nbsfo";
|
||||
|
||||
private CaesarCipher algorithm = new CaesarCipher();
|
||||
|
||||
@Test
|
||||
void givenSentenceAndShiftThree_whenCipher_thenCipheredMessageWithoutOverflow() {
|
||||
String cipheredSentence = algorithm.cipher(SENTENCE, 3);
|
||||
|
||||
assertThat(cipheredSentence)
|
||||
.isEqualTo(SENTENCE_SHIFTED_THREE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenSentenceAndShiftTen_whenCipher_thenCipheredMessageWithOverflow() {
|
||||
String cipheredSentence = algorithm.cipher(SENTENCE, 10);
|
||||
|
||||
assertThat(cipheredSentence)
|
||||
.isEqualTo(SENTENCE_SHIFTED_TEN);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenSentenceAndShiftThirtySix_whenCipher_thenCipheredLikeTenMessageWithOverflow() {
|
||||
String cipheredSentence = algorithm.cipher(SENTENCE, 36);
|
||||
|
||||
assertThat(cipheredSentence)
|
||||
.isEqualTo(SENTENCE_SHIFTED_TEN);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenSentenceShiftedThreeAndShiftThree_whenDecipher_thenOriginalSentenceWithoutOverflow() {
|
||||
String decipheredSentence = algorithm.decipher(SENTENCE_SHIFTED_THREE, 3);
|
||||
|
||||
assertThat(decipheredSentence)
|
||||
.isEqualTo(SENTENCE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenSentenceShiftedTenAndShiftTen_whenDecipher_thenOriginalSentenceWithOverflow() {
|
||||
String decipheredSentence = algorithm.decipher(SENTENCE_SHIFTED_TEN, 10);
|
||||
|
||||
assertThat(decipheredSentence)
|
||||
.isEqualTo(SENTENCE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenSentenceShiftedTenAndShiftThirtySix_whenDecipher_thenOriginalSentenceWithOverflow() {
|
||||
String decipheredSentence = algorithm.decipher(SENTENCE_SHIFTED_TEN, 36);
|
||||
|
||||
assertThat(decipheredSentence)
|
||||
.isEqualTo(SENTENCE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenSentenceShiftedThree_whenBreakCipher_thenOriginalSentence() {
|
||||
int offset = algorithm.breakCipher(SENTENCE_SHIFTED_THREE);
|
||||
|
||||
assertThat(offset)
|
||||
.isEqualTo(3);
|
||||
|
||||
assertThat(algorithm.decipher(SENTENCE_SHIFTED_THREE, offset))
|
||||
.isEqualTo(SENTENCE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenSentenceShiftedTen_whenBreakCipher_thenOriginalSentence() {
|
||||
int offset = algorithm.breakCipher(SENTENCE_SHIFTED_TEN);
|
||||
|
||||
assertThat(offset)
|
||||
.isEqualTo(10);
|
||||
|
||||
assertThat(algorithm.decipher(SENTENCE_SHIFTED_TEN, offset))
|
||||
.isEqualTo(SENTENCE);
|
||||
}
|
||||
}
|
11
algorithms-searching/README.md
Normal file
11
algorithms-searching/README.md
Normal file
@ -0,0 +1,11 @@
|
||||
## Algorithms - Searching
|
||||
|
||||
This module contains articles about searching algorithms.
|
||||
|
||||
### Relevant articles:
|
||||
- [Binary Search Algorithm in Java](https://www.baeldung.com/java-binary-search)
|
||||
- [Depth First Search in Java](https://www.baeldung.com/java-depth-first-search)
|
||||
- [Interpolation Search in Java](https://www.baeldung.com/java-interpolation-search)
|
||||
- [Breadth-First Search Algorithm in Java](https://www.baeldung.com/java-breadth-first-search)
|
||||
- [String Search Algorithms for Large Texts](https://www.baeldung.com/java-full-text-search-algorithms)
|
||||
- [Monte Carlo Tree Search for Tic-Tac-Toe Game](https://www.baeldung.com/java-monte-carlo-tree-search)
|
37
algorithms-searching/pom.xml
Normal file
37
algorithms-searching/pom.xml
Normal file
@ -0,0 +1,37 @@
|
||||
<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-searching</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>algorithms-searching</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>
|
||||
<finalName>algorithms-searching</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<org.assertj.core.version>3.9.0</org.assertj.core.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -1,55 +1,55 @@
|
||||
package com.baeldung.algorithms.binarysearch;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
public class BinarySearch {
|
||||
|
||||
public int runBinarySearchIteratively(int[] sortedArray, int key, int low, int high) {
|
||||
|
||||
int index = Integer.MAX_VALUE;
|
||||
|
||||
while (low <= high) {
|
||||
|
||||
int mid = (low + high) / 2;
|
||||
|
||||
if (sortedArray[mid] < key) {
|
||||
low = mid + 1;
|
||||
} else if (sortedArray[mid] > key) {
|
||||
high = mid - 1;
|
||||
} else if (sortedArray[mid] == key) {
|
||||
index = mid;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
public int runBinarySearchRecursively(int[] sortedArray, int key, int low, int high) {
|
||||
|
||||
int middle = (low + high) / 2;
|
||||
if (high < low) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (key == sortedArray[middle]) {
|
||||
return middle;
|
||||
} else if (key < sortedArray[middle]) {
|
||||
return runBinarySearchRecursively(sortedArray, key, low, middle - 1);
|
||||
} else {
|
||||
return runBinarySearchRecursively(sortedArray, key, middle + 1, high);
|
||||
}
|
||||
}
|
||||
|
||||
public int runBinarySearchUsingJavaArrays(int[] sortedArray, Integer key) {
|
||||
int index = Arrays.binarySearch(sortedArray, key);
|
||||
return index;
|
||||
}
|
||||
|
||||
public int runBinarySearchUsingJavaCollections(List<Integer> sortedList, Integer key) {
|
||||
int index = Collections.binarySearch(sortedList, key);
|
||||
return index;
|
||||
}
|
||||
|
||||
}
|
||||
package com.baeldung.algorithms.binarysearch;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
public class BinarySearch {
|
||||
|
||||
public int runBinarySearchIteratively(int[] sortedArray, int key, int low, int high) {
|
||||
|
||||
int index = Integer.MAX_VALUE;
|
||||
|
||||
while (low <= high) {
|
||||
|
||||
int mid = (low + high) / 2;
|
||||
|
||||
if (sortedArray[mid] < key) {
|
||||
low = mid + 1;
|
||||
} else if (sortedArray[mid] > key) {
|
||||
high = mid - 1;
|
||||
} else if (sortedArray[mid] == key) {
|
||||
index = mid;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
public int runBinarySearchRecursively(int[] sortedArray, int key, int low, int high) {
|
||||
|
||||
int middle = (low + high) / 2;
|
||||
if (high < low) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (key == sortedArray[middle]) {
|
||||
return middle;
|
||||
} else if (key < sortedArray[middle]) {
|
||||
return runBinarySearchRecursively(sortedArray, key, low, middle - 1);
|
||||
} else {
|
||||
return runBinarySearchRecursively(sortedArray, key, middle + 1, high);
|
||||
}
|
||||
}
|
||||
|
||||
public int runBinarySearchUsingJavaArrays(int[] sortedArray, Integer key) {
|
||||
int index = Arrays.binarySearch(sortedArray, key);
|
||||
return index;
|
||||
}
|
||||
|
||||
public int runBinarySearchUsingJavaCollections(List<Integer> sortedList, Integer key) {
|
||||
int index = Collections.binarySearch(sortedList, key);
|
||||
return index;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,227 @@
|
||||
package com.baeldung.algorithms.dfs;
|
||||
|
||||
import java.util.LinkedList;
|
||||
import java.util.Queue;
|
||||
import java.util.Stack;
|
||||
|
||||
public class BinaryTree {
|
||||
|
||||
Node root;
|
||||
|
||||
public void add(int value) {
|
||||
root = addRecursive(root, value);
|
||||
}
|
||||
|
||||
private Node addRecursive(Node current, int value) {
|
||||
|
||||
if (current == null) {
|
||||
return new Node(value);
|
||||
}
|
||||
|
||||
if (value < current.value) {
|
||||
current.left = addRecursive(current.left, value);
|
||||
} else if (value > current.value) {
|
||||
current.right = addRecursive(current.right, value);
|
||||
}
|
||||
|
||||
return current;
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return root == null;
|
||||
}
|
||||
|
||||
public int getSize() {
|
||||
return getSizeRecursive(root);
|
||||
}
|
||||
|
||||
private int getSizeRecursive(Node current) {
|
||||
return current == null ? 0 : getSizeRecursive(current.left) + 1 + getSizeRecursive(current.right);
|
||||
}
|
||||
|
||||
public boolean containsNode(int value) {
|
||||
return containsNodeRecursive(root, value);
|
||||
}
|
||||
|
||||
private boolean containsNodeRecursive(Node current, int value) {
|
||||
if (current == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (value == current.value) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return value < current.value
|
||||
? containsNodeRecursive(current.left, value)
|
||||
: containsNodeRecursive(current.right, value);
|
||||
}
|
||||
|
||||
public void delete(int value) {
|
||||
root = deleteRecursive(root, value);
|
||||
}
|
||||
|
||||
private Node deleteRecursive(Node current, int value) {
|
||||
if (current == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (value == current.value) {
|
||||
// Case 1: no children
|
||||
if (current.left == null && current.right == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Case 2: only 1 child
|
||||
if (current.right == null) {
|
||||
return current.left;
|
||||
}
|
||||
|
||||
if (current.left == null) {
|
||||
return current.right;
|
||||
}
|
||||
|
||||
// Case 3: 2 children
|
||||
int smallestValue = findSmallestValue(current.right);
|
||||
current.value = smallestValue;
|
||||
current.right = deleteRecursive(current.right, smallestValue);
|
||||
return current;
|
||||
}
|
||||
if (value < current.value) {
|
||||
current.left = deleteRecursive(current.left, value);
|
||||
return current;
|
||||
}
|
||||
|
||||
current.right = deleteRecursive(current.right, value);
|
||||
return current;
|
||||
}
|
||||
|
||||
private int findSmallestValue(Node root) {
|
||||
return root.left == null ? root.value : findSmallestValue(root.left);
|
||||
}
|
||||
|
||||
public void traverseInOrder(Node node) {
|
||||
if (node != null) {
|
||||
traverseInOrder(node.left);
|
||||
visit(node.value);
|
||||
traverseInOrder(node.right);
|
||||
}
|
||||
}
|
||||
|
||||
public void traversePreOrder(Node node) {
|
||||
if (node != null) {
|
||||
visit(node.value);
|
||||
traversePreOrder(node.left);
|
||||
traversePreOrder(node.right);
|
||||
}
|
||||
}
|
||||
|
||||
public void traversePostOrder(Node node) {
|
||||
if (node != null) {
|
||||
traversePostOrder(node.left);
|
||||
traversePostOrder(node.right);
|
||||
visit(node.value);
|
||||
}
|
||||
}
|
||||
|
||||
public void traverseLevelOrder() {
|
||||
if (root == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
Queue<Node> nodes = new LinkedList<>();
|
||||
nodes.add(root);
|
||||
|
||||
while (!nodes.isEmpty()) {
|
||||
|
||||
Node node = nodes.remove();
|
||||
|
||||
System.out.print(" " + node.value);
|
||||
|
||||
if (node.left != null) {
|
||||
nodes.add(node.left);
|
||||
}
|
||||
|
||||
if (node.left != null) {
|
||||
nodes.add(node.right);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void traverseInOrderWithoutRecursion() {
|
||||
Stack<Node> stack = new Stack<Node>();
|
||||
Node current = root;
|
||||
stack.push(root);
|
||||
while(! stack.isEmpty()) {
|
||||
while(current.left != null) {
|
||||
current = current.left;
|
||||
stack.push(current);
|
||||
}
|
||||
current = stack.pop();
|
||||
visit(current.value);
|
||||
if(current.right != null) {
|
||||
current = current.right;
|
||||
stack.push(current);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void traversePreOrderWithoutRecursion() {
|
||||
Stack<Node> stack = new Stack<Node>();
|
||||
Node current = root;
|
||||
stack.push(root);
|
||||
while(! stack.isEmpty()) {
|
||||
current = stack.pop();
|
||||
visit(current.value);
|
||||
|
||||
if(current.right != null)
|
||||
stack.push(current.right);
|
||||
|
||||
if(current.left != null)
|
||||
stack.push(current.left);
|
||||
}
|
||||
}
|
||||
|
||||
public void traversePostOrderWithoutRecursion() {
|
||||
Stack<Node> stack = new Stack<Node>();
|
||||
Node prev = root;
|
||||
Node current = root;
|
||||
stack.push(root);
|
||||
|
||||
while (!stack.isEmpty()) {
|
||||
current = stack.peek();
|
||||
boolean hasChild = (current.left != null || current.right != null);
|
||||
boolean isPrevLastChild = (prev == current.right || (prev == current.left && current.right == null));
|
||||
|
||||
if (!hasChild || isPrevLastChild) {
|
||||
current = stack.pop();
|
||||
visit(current.value);
|
||||
prev = current;
|
||||
} else {
|
||||
if (current.right != null) {
|
||||
stack.push(current.right);
|
||||
}
|
||||
if (current.left != null) {
|
||||
stack.push(current.left);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void visit(int value) {
|
||||
System.out.print(" " + value);
|
||||
}
|
||||
|
||||
class Node {
|
||||
int value;
|
||||
Node left;
|
||||
Node right;
|
||||
|
||||
Node(int value) {
|
||||
this.value = value;
|
||||
right = null;
|
||||
left = null;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.graph;
|
||||
package com.baeldung.algorithms.dfs;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
@ -1,194 +1,194 @@
|
||||
package com.baeldung.algorithms.string.search;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.Random;
|
||||
|
||||
public class StringSearchAlgorithms {
|
||||
public static long getBiggerPrime(int m) {
|
||||
BigInteger prime = BigInteger.probablePrime(getNumberOfBits(m) + 1, new Random());
|
||||
return prime.longValue();
|
||||
}
|
||||
|
||||
public static long getLowerPrime(long number) {
|
||||
BigInteger prime = BigInteger.probablePrime(getNumberOfBits(number) - 1, new Random());
|
||||
return prime.longValue();
|
||||
}
|
||||
|
||||
private static int getNumberOfBits(final int number) {
|
||||
return Integer.SIZE - Integer.numberOfLeadingZeros(number);
|
||||
}
|
||||
|
||||
private static int getNumberOfBits(final long number) {
|
||||
return Long.SIZE - Long.numberOfLeadingZeros(number);
|
||||
}
|
||||
|
||||
public static int simpleTextSearch(char[] pattern, char[] text) {
|
||||
int patternSize = pattern.length;
|
||||
int textSize = text.length;
|
||||
|
||||
int i = 0;
|
||||
|
||||
while ((i + patternSize) <= textSize) {
|
||||
int j = 0;
|
||||
while (text[i + j] == pattern[j]) {
|
||||
j += 1;
|
||||
if (j >= patternSize)
|
||||
return i;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
public static int RabinKarpMethod(char[] pattern, char[] text) {
|
||||
int patternSize = pattern.length; // m
|
||||
int textSize = text.length; // n
|
||||
|
||||
long prime = getBiggerPrime(patternSize);
|
||||
|
||||
long r = 1;
|
||||
for (int i = 0; i < patternSize - 1; i++) {
|
||||
r *= 2;
|
||||
r = r % prime;
|
||||
}
|
||||
|
||||
long[] t = new long[textSize];
|
||||
t[0] = 0;
|
||||
|
||||
long pfinger = 0;
|
||||
|
||||
for (int j = 0; j < patternSize; j++) {
|
||||
t[0] = (2 * t[0] + text[j]) % prime;
|
||||
pfinger = (2 * pfinger + pattern[j]) % prime;
|
||||
}
|
||||
|
||||
int i = 0;
|
||||
boolean passed = false;
|
||||
|
||||
int diff = textSize - patternSize;
|
||||
for (i = 0; i <= diff; i++) {
|
||||
if (t[i] == pfinger) {
|
||||
passed = true;
|
||||
for (int k = 0; k < patternSize; k++) {
|
||||
if (text[i + k] != pattern[k]) {
|
||||
passed = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (passed) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
if (i < diff) {
|
||||
long value = 2 * (t[i] - r * text[i]) + text[i + patternSize];
|
||||
t[i + 1] = ((value % prime) + prime) % prime;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
|
||||
}
|
||||
|
||||
public static int KnuthMorrisPrattSearch(char[] pattern, char[] text) {
|
||||
int patternSize = pattern.length; // m
|
||||
int textSize = text.length; // n
|
||||
|
||||
int i = 0, j = 0;
|
||||
|
||||
int[] shift = KnuthMorrisPrattShift(pattern);
|
||||
|
||||
while ((i + patternSize) <= textSize) {
|
||||
while (text[i + j] == pattern[j]) {
|
||||
j += 1;
|
||||
if (j >= patternSize)
|
||||
return i;
|
||||
}
|
||||
|
||||
if (j > 0) {
|
||||
i += shift[j - 1];
|
||||
j = Math.max(j - shift[j - 1], 0);
|
||||
} else {
|
||||
i++;
|
||||
j = 0;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
public static int[] KnuthMorrisPrattShift(char[] pattern) {
|
||||
int patternSize = pattern.length;
|
||||
|
||||
int[] shift = new int[patternSize];
|
||||
shift[0] = 1;
|
||||
|
||||
int i = 1, j = 0;
|
||||
|
||||
while ((i + j) < patternSize) {
|
||||
if (pattern[i + j] == pattern[j]) {
|
||||
shift[i + j] = i;
|
||||
j++;
|
||||
} else {
|
||||
if (j == 0)
|
||||
shift[i] = i + 1;
|
||||
|
||||
if (j > 0) {
|
||||
i = i + shift[j - 1];
|
||||
j = Math.max(j - shift[j - 1], 0);
|
||||
} else {
|
||||
i = i + 1;
|
||||
j = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
return shift;
|
||||
}
|
||||
|
||||
public static int BoyerMooreHorspoolSimpleSearch(char[] pattern, char[] text) {
|
||||
int patternSize = pattern.length;
|
||||
int textSize = text.length;
|
||||
|
||||
int i = 0, j = 0;
|
||||
|
||||
while ((i + patternSize) <= textSize) {
|
||||
j = patternSize - 1;
|
||||
while (text[i + j] == pattern[j]) {
|
||||
j--;
|
||||
if (j < 0)
|
||||
return i;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
public static int BoyerMooreHorspoolSearch(char[] pattern, char[] text) {
|
||||
|
||||
int shift[] = new int[256];
|
||||
|
||||
for (int k = 0; k < 256; k++) {
|
||||
shift[k] = pattern.length;
|
||||
}
|
||||
|
||||
for (int k = 0; k < pattern.length - 1; k++) {
|
||||
shift[pattern[k]] = pattern.length - 1 - k;
|
||||
}
|
||||
|
||||
int i = 0, j = 0;
|
||||
|
||||
while ((i + pattern.length) <= text.length) {
|
||||
j = pattern.length - 1;
|
||||
|
||||
while (text[i + j] == pattern[j]) {
|
||||
j -= 1;
|
||||
if (j < 0)
|
||||
return i;
|
||||
}
|
||||
|
||||
i = i + shift[text[i + pattern.length - 1]];
|
||||
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
package com.baeldung.algorithms.textsearch;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.Random;
|
||||
|
||||
public class TextSearchAlgorithms {
|
||||
public static long getBiggerPrime(int m) {
|
||||
BigInteger prime = BigInteger.probablePrime(getNumberOfBits(m) + 1, new Random());
|
||||
return prime.longValue();
|
||||
}
|
||||
|
||||
public static long getLowerPrime(long number) {
|
||||
BigInteger prime = BigInteger.probablePrime(getNumberOfBits(number) - 1, new Random());
|
||||
return prime.longValue();
|
||||
}
|
||||
|
||||
private static int getNumberOfBits(final int number) {
|
||||
return Integer.SIZE - Integer.numberOfLeadingZeros(number);
|
||||
}
|
||||
|
||||
private static int getNumberOfBits(final long number) {
|
||||
return Long.SIZE - Long.numberOfLeadingZeros(number);
|
||||
}
|
||||
|
||||
public static int simpleTextSearch(char[] pattern, char[] text) {
|
||||
int patternSize = pattern.length;
|
||||
int textSize = text.length;
|
||||
|
||||
int i = 0;
|
||||
|
||||
while ((i + patternSize) <= textSize) {
|
||||
int j = 0;
|
||||
while (text[i + j] == pattern[j]) {
|
||||
j += 1;
|
||||
if (j >= patternSize)
|
||||
return i;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
public static int RabinKarpMethod(char[] pattern, char[] text) {
|
||||
int patternSize = pattern.length; // m
|
||||
int textSize = text.length; // n
|
||||
|
||||
long prime = getBiggerPrime(patternSize);
|
||||
|
||||
long r = 1;
|
||||
for (int i = 0; i < patternSize - 1; i++) {
|
||||
r *= 2;
|
||||
r = r % prime;
|
||||
}
|
||||
|
||||
long[] t = new long[textSize];
|
||||
t[0] = 0;
|
||||
|
||||
long pfinger = 0;
|
||||
|
||||
for (int j = 0; j < patternSize; j++) {
|
||||
t[0] = (2 * t[0] + text[j]) % prime;
|
||||
pfinger = (2 * pfinger + pattern[j]) % prime;
|
||||
}
|
||||
|
||||
int i = 0;
|
||||
boolean passed = false;
|
||||
|
||||
int diff = textSize - patternSize;
|
||||
for (i = 0; i <= diff; i++) {
|
||||
if (t[i] == pfinger) {
|
||||
passed = true;
|
||||
for (int k = 0; k < patternSize; k++) {
|
||||
if (text[i + k] != pattern[k]) {
|
||||
passed = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (passed) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
if (i < diff) {
|
||||
long value = 2 * (t[i] - r * text[i]) + text[i + patternSize];
|
||||
t[i + 1] = ((value % prime) + prime) % prime;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
|
||||
}
|
||||
|
||||
public static int KnuthMorrisPrattSearch(char[] pattern, char[] text) {
|
||||
int patternSize = pattern.length; // m
|
||||
int textSize = text.length; // n
|
||||
|
||||
int i = 0, j = 0;
|
||||
|
||||
int[] shift = KnuthMorrisPrattShift(pattern);
|
||||
|
||||
while ((i + patternSize) <= textSize) {
|
||||
while (text[i + j] == pattern[j]) {
|
||||
j += 1;
|
||||
if (j >= patternSize)
|
||||
return i;
|
||||
}
|
||||
|
||||
if (j > 0) {
|
||||
i += shift[j - 1];
|
||||
j = Math.max(j - shift[j - 1], 0);
|
||||
} else {
|
||||
i++;
|
||||
j = 0;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
public static int[] KnuthMorrisPrattShift(char[] pattern) {
|
||||
int patternSize = pattern.length;
|
||||
|
||||
int[] shift = new int[patternSize];
|
||||
shift[0] = 1;
|
||||
|
||||
int i = 1, j = 0;
|
||||
|
||||
while ((i + j) < patternSize) {
|
||||
if (pattern[i + j] == pattern[j]) {
|
||||
shift[i + j] = i;
|
||||
j++;
|
||||
} else {
|
||||
if (j == 0)
|
||||
shift[i] = i + 1;
|
||||
|
||||
if (j > 0) {
|
||||
i = i + shift[j - 1];
|
||||
j = Math.max(j - shift[j - 1], 0);
|
||||
} else {
|
||||
i = i + 1;
|
||||
j = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
return shift;
|
||||
}
|
||||
|
||||
public static int BoyerMooreHorspoolSimpleSearch(char[] pattern, char[] text) {
|
||||
int patternSize = pattern.length;
|
||||
int textSize = text.length;
|
||||
|
||||
int i = 0, j = 0;
|
||||
|
||||
while ((i + patternSize) <= textSize) {
|
||||
j = patternSize - 1;
|
||||
while (text[i + j] == pattern[j]) {
|
||||
j--;
|
||||
if (j < 0)
|
||||
return i;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
public static int BoyerMooreHorspoolSearch(char[] pattern, char[] text) {
|
||||
|
||||
int shift[] = new int[256];
|
||||
|
||||
for (int k = 0; k < 256; k++) {
|
||||
shift[k] = pattern.length;
|
||||
}
|
||||
|
||||
for (int k = 0; k < pattern.length - 1; k++) {
|
||||
shift[pattern[k]] = pattern.length - 1 - k;
|
||||
}
|
||||
|
||||
int i = 0, j = 0;
|
||||
|
||||
while ((i + pattern.length) <= text.length) {
|
||||
j = pattern.length - 1;
|
||||
|
||||
while (text[i + j] == pattern[j]) {
|
||||
j -= 1;
|
||||
if (j < 0)
|
||||
return i;
|
||||
}
|
||||
|
||||
i = i + shift[text[i + pattern.length - 1]];
|
||||
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
}
|
@ -1,43 +1,41 @@
|
||||
package com.baeldung.algorithms.binarysearch;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import com.baeldung.algorithms.binarysearch.BinarySearch;
|
||||
|
||||
public class BinarySearchUnitTest {
|
||||
|
||||
int[] sortedArray = { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 };
|
||||
int key = 6;
|
||||
int expectedIndexForSearchKey = 7;
|
||||
int low = 0;
|
||||
int high = sortedArray.length - 1;
|
||||
List<Integer> sortedList = Arrays.asList(0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9);
|
||||
|
||||
@Test
|
||||
public void givenASortedArrayOfIntegers_whenBinarySearchRunIterativelyForANumber_thenGetIndexOfTheNumber() {
|
||||
BinarySearch binSearch = new BinarySearch();
|
||||
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchIteratively(sortedArray, key, low, high));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenASortedArrayOfIntegers_whenBinarySearchRunRecursivelyForANumber_thenGetIndexOfTheNumber() {
|
||||
BinarySearch binSearch = new BinarySearch();
|
||||
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchRecursively(sortedArray, key, low, high));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenASortedArrayOfIntegers_whenBinarySearchRunUsingArraysClassStaticMethodForANumber_thenGetIndexOfTheNumber() {
|
||||
BinarySearch binSearch = new BinarySearch();
|
||||
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaArrays(sortedArray, key));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenASortedListOfIntegers_whenBinarySearchRunUsingCollectionsClassStaticMethodForANumber_thenGetIndexOfTheNumber() {
|
||||
BinarySearch binSearch = new BinarySearch();
|
||||
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaCollections(sortedList, key));
|
||||
}
|
||||
|
||||
}
|
||||
package com.baeldung.algorithms.binarysearch;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class BinarySearchUnitTest {
|
||||
|
||||
int[] sortedArray = { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 };
|
||||
int key = 6;
|
||||
int expectedIndexForSearchKey = 7;
|
||||
int low = 0;
|
||||
int high = sortedArray.length - 1;
|
||||
List<Integer> sortedList = Arrays.asList(0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9);
|
||||
|
||||
@Test
|
||||
public void givenASortedArrayOfIntegers_whenBinarySearchRunIterativelyForANumber_thenGetIndexOfTheNumber() {
|
||||
BinarySearch binSearch = new BinarySearch();
|
||||
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchIteratively(sortedArray, key, low, high));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenASortedArrayOfIntegers_whenBinarySearchRunRecursivelyForANumber_thenGetIndexOfTheNumber() {
|
||||
BinarySearch binSearch = new BinarySearch();
|
||||
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchRecursively(sortedArray, key, low, high));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenASortedArrayOfIntegers_whenBinarySearchRunUsingArraysClassStaticMethodForANumber_thenGetIndexOfTheNumber() {
|
||||
BinarySearch binSearch = new BinarySearch();
|
||||
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaArrays(sortedArray, key));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenASortedListOfIntegers_whenBinarySearchRunUsingCollectionsClassStaticMethodForANumber_thenGetIndexOfTheNumber() {
|
||||
BinarySearch binSearch = new BinarySearch();
|
||||
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaCollections(sortedList, key));
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,136 @@
|
||||
package com.baeldung.algorithms.dfs;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class BinaryTreeUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenABinaryTree_WhenAddingElements_ThenTreeNotEmpty() {
|
||||
|
||||
BinaryTree bt = createBinaryTree();
|
||||
|
||||
assertTrue(!bt.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenABinaryTree_WhenAddingElements_ThenTreeContainsThoseElements() {
|
||||
|
||||
BinaryTree bt = createBinaryTree();
|
||||
|
||||
assertTrue(bt.containsNode(6));
|
||||
assertTrue(bt.containsNode(4));
|
||||
|
||||
assertFalse(bt.containsNode(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenABinaryTree_WhenAddingExistingElement_ThenElementIsNotAdded() {
|
||||
|
||||
BinaryTree bt = createBinaryTree();
|
||||
|
||||
int initialSize = bt.getSize();
|
||||
|
||||
assertTrue(bt.containsNode(3));
|
||||
bt.add(3);
|
||||
assertEquals(initialSize, bt.getSize());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenABinaryTree_WhenLookingForNonExistingElement_ThenReturnsFalse() {
|
||||
|
||||
BinaryTree bt = createBinaryTree();
|
||||
|
||||
assertFalse(bt.containsNode(99));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenABinaryTree_WhenDeletingElements_ThenTreeDoesNotContainThoseElements() {
|
||||
|
||||
BinaryTree bt = createBinaryTree();
|
||||
|
||||
assertTrue(bt.containsNode(9));
|
||||
bt.delete(9);
|
||||
assertFalse(bt.containsNode(9));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenABinaryTree_WhenDeletingNonExistingElement_ThenTreeDoesNotDelete() {
|
||||
|
||||
BinaryTree bt = createBinaryTree();
|
||||
|
||||
int initialSize = bt.getSize();
|
||||
|
||||
assertFalse(bt.containsNode(99));
|
||||
bt.delete(99);
|
||||
assertFalse(bt.containsNode(99));
|
||||
assertEquals(initialSize, bt.getSize());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void it_deletes_the_root() {
|
||||
int value = 12;
|
||||
BinaryTree bt = new BinaryTree();
|
||||
bt.add(value);
|
||||
|
||||
assertTrue(bt.containsNode(value));
|
||||
bt.delete(value);
|
||||
assertFalse(bt.containsNode(value));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenABinaryTree_WhenTraversingInOrder_ThenPrintValues() {
|
||||
|
||||
BinaryTree bt = createBinaryTree();
|
||||
|
||||
bt.traverseInOrder(bt.root);
|
||||
System.out.println();
|
||||
bt.traverseInOrderWithoutRecursion();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenABinaryTree_WhenTraversingPreOrder_ThenPrintValues() {
|
||||
|
||||
BinaryTree bt = createBinaryTree();
|
||||
|
||||
bt.traversePreOrder(bt.root);
|
||||
System.out.println();
|
||||
bt.traversePreOrderWithoutRecursion();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenABinaryTree_WhenTraversingPostOrder_ThenPrintValues() {
|
||||
|
||||
BinaryTree bt = createBinaryTree();
|
||||
|
||||
bt.traversePostOrder(bt.root);
|
||||
System.out.println();
|
||||
bt.traversePostOrderWithoutRecursion();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenABinaryTree_WhenTraversingLevelOrder_ThenPrintValues() {
|
||||
|
||||
BinaryTree bt = createBinaryTree();
|
||||
|
||||
bt.traverseLevelOrder();
|
||||
}
|
||||
|
||||
private BinaryTree createBinaryTree() {
|
||||
BinaryTree bt = new BinaryTree();
|
||||
|
||||
bt.add(6);
|
||||
bt.add(4);
|
||||
bt.add(8);
|
||||
bt.add(3);
|
||||
bt.add(5);
|
||||
bt.add(7);
|
||||
bt.add(9);
|
||||
|
||||
return bt;
|
||||
}
|
||||
|
||||
}
|
@ -1,7 +1,8 @@
|
||||
package com.baeldung.graph;
|
||||
package com.baeldung.algorithms.dfs;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.baeldung.algorithms.dfs.Graph;
|
||||
import org.junit.Test;
|
||||
|
||||
public class GraphUnitTest {
|
@ -1,10 +1,10 @@
|
||||
package com.baeldung.algorithms.interpolationsearch;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class InterpolationSearchUnitTest {
|
||||
|
||||
private int[] myData;
|
@ -0,0 +1,23 @@
|
||||
package com.baeldung.algorithms.textsearch;
|
||||
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class TextSearchAlgorithmsUnitTest {
|
||||
|
||||
|
||||
@Test
|
||||
public void testStringSearchAlgorithms() {
|
||||
String text = "This is some nice text.";
|
||||
String pattern = "some";
|
||||
|
||||
int realPosition = text.indexOf(pattern);
|
||||
Assert.assertTrue(realPosition == TextSearchAlgorithms.simpleTextSearch(pattern.toCharArray(), text.toCharArray()));
|
||||
Assert.assertTrue(realPosition == TextSearchAlgorithms.RabinKarpMethod(pattern.toCharArray(), text.toCharArray()));
|
||||
Assert.assertTrue(realPosition == TextSearchAlgorithms.KnuthMorrisPrattSearch(pattern.toCharArray(), text.toCharArray()));
|
||||
Assert.assertTrue(realPosition == TextSearchAlgorithms.BoyerMooreHorspoolSimpleSearch(pattern.toCharArray(), text.toCharArray()));
|
||||
Assert.assertTrue(realPosition == TextSearchAlgorithms.BoyerMooreHorspoolSearch(pattern.toCharArray(), text.toCharArray()));
|
||||
}
|
||||
|
||||
}
|
@ -15,7 +15,7 @@ public class LocalDbCreationRule extends ExternalResource {
|
||||
@Override
|
||||
protected void before() throws Exception {
|
||||
String port = "8000";
|
||||
this.server = ServerRunner.createServerFromCommandLineArgs(new String[]{"-inMemory", "-port", port});
|
||||
this.server = ServerRunner.createServerFromCommandLineArgs(new String[]{"-inMemory","-sharedDb" ,"-port", port});
|
||||
server.start();
|
||||
}
|
||||
|
||||
|
@ -7,3 +7,4 @@ This module contains articles about automatic code generation
|
||||
- [Introduction to AutoValue](https://www.baeldung.com/introduction-to-autovalue)
|
||||
- [Introduction to AutoFactory](https://www.baeldung.com/autofactory)
|
||||
- [Google AutoService](https://www.baeldung.com/google-autoservice)
|
||||
- [Defensive Copies for Collections Using AutoValue](https://www.baeldung.com/autovalue-defensive-copies)
|
||||
|
@ -9,4 +9,5 @@ This module contains articles about the Java List collection
|
||||
- [List of Primitive Integer Values in Java](https://www.baeldung.com/java-list-primitive-int)
|
||||
- [Performance Comparison of Primitive Lists in Java](https://www.baeldung.com/java-list-primitive-performance)
|
||||
- [Filtering a Java Collection by a List](https://www.baeldung.com/java-filter-collection-by-list)
|
||||
- [How to Count Duplicate Elements in Arraylist](https://www.baeldung.com/java-count-duplicate-elements-arraylist)
|
||||
- [[<-- Prev]](/core-java-modules/core-java-collections-list-2)
|
||||
|
@ -27,6 +27,16 @@
|
||||
|
||||
<build>
|
||||
<finalName>core-java-concurrency-advanced-3</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>${maven.compiler.source}</source>
|
||||
<target>${maven.compiler.target}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
@ -37,6 +47,8 @@
|
||||
|
||||
<properties>
|
||||
<assertj.version>3.14.0</assertj.version>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
@ -0,0 +1,53 @@
|
||||
package com.baeldung.commonissues;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
public class CollectionsConcurrencyIssues {
|
||||
|
||||
private void putIfAbsentList_NonAtomicOperation_ProneToConcurrencyIssues() {
|
||||
List<String> list = Collections.synchronizedList(new ArrayList<>());
|
||||
if (!list.contains("foo")) {
|
||||
list.add("foo");
|
||||
}
|
||||
}
|
||||
|
||||
private void putIfAbsentList_AtomicOperation_ThreadSafe() {
|
||||
List<String> list = Collections.synchronizedList(new ArrayList<>());
|
||||
synchronized (list) {
|
||||
if (!list.contains("foo")) {
|
||||
list.add("foo");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void putIfAbsentMap_NonAtomicOperation_ProneToConcurrencyIssues() {
|
||||
Map<String, String> map = new ConcurrentHashMap<>();
|
||||
if (!map.containsKey("foo")) {
|
||||
map.put("foo", "bar");
|
||||
}
|
||||
}
|
||||
|
||||
private void putIfAbsentMap_AtomicOperation_BetterApproach() {
|
||||
Map<String, String> map = new ConcurrentHashMap<>();
|
||||
synchronized (map) {
|
||||
if (!map.containsKey("foo")) {
|
||||
map.put("foo", "bar");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void putIfAbsentMap_AtomicOperation_BestApproach() {
|
||||
Map<String, String> map = new ConcurrentHashMap<>();
|
||||
map.putIfAbsent("foo", "bar");
|
||||
}
|
||||
|
||||
private void computeIfAbsentMap_AtomicOperation() {
|
||||
Map<String, String> map = new ConcurrentHashMap<>();
|
||||
map.computeIfAbsent("foo", key -> key + "bar");
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
package com.baeldung.commonissues;
|
||||
|
||||
class Counter {
|
||||
private int counter = 0;
|
||||
|
||||
public void increment() {
|
||||
counter++;
|
||||
}
|
||||
|
||||
public int getValue() {
|
||||
return counter;
|
||||
}
|
||||
}
|
@ -0,0 +1,42 @@
|
||||
package com.baeldung.commonissues;
|
||||
|
||||
public class DeadlockExample {
|
||||
|
||||
public static Object lock1 = new Object();
|
||||
public static Object lock2 = new Object();
|
||||
|
||||
public static void main(String args[]) {
|
||||
Thread threadA = new Thread(() -> {
|
||||
synchronized (lock1) {
|
||||
System.out.println("ThreadA: Holding lock 1...");
|
||||
sleep();
|
||||
System.out.println("ThreadA: Waiting for lock 2...");
|
||||
|
||||
synchronized (lock2) {
|
||||
System.out.println("ThreadA: Holding lock 1 & 2...");
|
||||
}
|
||||
}
|
||||
});
|
||||
Thread threadB = new Thread(() -> {
|
||||
synchronized (lock2) {
|
||||
System.out.println("ThreadB: Holding lock 2...");
|
||||
sleep();
|
||||
System.out.println("ThreadB: Waiting for lock 1...");
|
||||
|
||||
synchronized (lock1) {
|
||||
System.out.println("ThreadB: Holding lock 1 & 2...");
|
||||
}
|
||||
}
|
||||
});
|
||||
threadA.start();
|
||||
threadB.start();
|
||||
}
|
||||
|
||||
private static void sleep() {
|
||||
try {
|
||||
Thread.sleep(100);
|
||||
} catch (InterruptedException e) {
|
||||
throw new RuntimeException();
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,35 @@
|
||||
package com.baeldung.commonissues;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
public class SimpleDateFormatThreadUnsafetyExample {
|
||||
|
||||
private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
|
||||
|
||||
public static void main(String[] args) {
|
||||
String dateStr = "2019-10-29T11:12:21";
|
||||
|
||||
ExecutorService executorService = Executors.newFixedThreadPool(10);
|
||||
|
||||
for (int i = 0; i < 20; i++) {
|
||||
executorService.submit(() -> parseDate(dateStr));
|
||||
}
|
||||
|
||||
executorService.shutdown();
|
||||
}
|
||||
|
||||
private static void parseDate(String dateStr) {
|
||||
try {
|
||||
Date date = simpleDateFormat.parse(dateStr);
|
||||
System.out.println("Successfully Parsed Date " + date);
|
||||
} catch (ParseException e) {
|
||||
System.out.println("ParseError " + e.getMessage());
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
package com.baeldung.commonissues;
|
||||
|
||||
class SynchronizedCounter {
|
||||
private int counter = 0;
|
||||
|
||||
public synchronized void increment() {
|
||||
counter++;
|
||||
}
|
||||
|
||||
public synchronized int getValue() {
|
||||
return counter;
|
||||
}
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
package com.baeldung.commonissues;
|
||||
|
||||
class SynchronizedVolatileCounter {
|
||||
private volatile int counter = 0;
|
||||
|
||||
public synchronized void increment() {
|
||||
counter++;
|
||||
}
|
||||
|
||||
public int getValue() {
|
||||
return counter;
|
||||
}
|
||||
}
|
@ -18,8 +18,11 @@ public class CounterUnitTest {
|
||||
Counter counter = new Counter();
|
||||
Future<Integer> future1 = (Future<Integer>) executorService.submit(new CounterCallable(counter));
|
||||
Future<Integer> future2 = (Future<Integer>) executorService.submit(new CounterCallable(counter));
|
||||
|
||||
assertThat(future1.get()).isEqualTo(1);
|
||||
assertThat(future2.get()).isEqualTo(2);
|
||||
|
||||
// Just to make sure both are completed
|
||||
future1.get();
|
||||
future2.get();
|
||||
|
||||
assertThat(counter.getCounter()).isEqualTo(2);
|
||||
}
|
||||
}
|
||||
|
@ -18,8 +18,11 @@ public class ExtrinsicLockCounterUnitTest {
|
||||
ExtrinsicLockCounter counter = new ExtrinsicLockCounter();
|
||||
Future<Integer> future1 = (Future<Integer>) executorService.submit(new ExtrinsicLockCounterCallable(counter));
|
||||
Future<Integer> future2 = (Future<Integer>) executorService.submit(new ExtrinsicLockCounterCallable(counter));
|
||||
|
||||
assertThat(future1.get()).isEqualTo(1);
|
||||
assertThat(future2.get()).isEqualTo(2);
|
||||
|
||||
// Just to make sure both are completed
|
||||
future1.get();
|
||||
future2.get();
|
||||
|
||||
assertThat(counter.getCounter()).isEqualTo(2);
|
||||
}
|
||||
}
|
||||
|
@ -11,15 +11,18 @@ import java.util.concurrent.Future;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class ReentrantLockCounterUnitTest {
|
||||
|
||||
|
||||
@Test
|
||||
public void whenCalledIncrementCounter_thenCorrect() throws Exception {
|
||||
ExecutorService executorService = Executors.newFixedThreadPool(2);
|
||||
ReentrantLockCounter counter = new ReentrantLockCounter();
|
||||
Future<Integer> future1 = (Future<Integer>) executorService.submit(new ReentrantLockCounterCallable(counter));
|
||||
Future<Integer> future2 = (Future<Integer>) executorService.submit(new ReentrantLockCounterCallable(counter));
|
||||
|
||||
assertThat(future1.get()).isEqualTo(1);
|
||||
assertThat(future2.get()).isEqualTo(2);
|
||||
|
||||
// Just to make sure both are completed
|
||||
future1.get();
|
||||
future2.get();
|
||||
|
||||
assertThat(counter.getCounter()).isEqualTo(2);
|
||||
}
|
||||
}
|
||||
|
@ -11,16 +11,19 @@ import java.util.concurrent.Future;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class ReentrantReadWriteLockCounterUnitTest {
|
||||
|
||||
|
||||
@Test
|
||||
public void whenCalledIncrementCounter_thenCorrect() throws Exception {
|
||||
ExecutorService executorService = Executors.newFixedThreadPool(2);
|
||||
ReentrantReadWriteLockCounter counter = new ReentrantReadWriteLockCounter();
|
||||
Future<Integer> future1 = (Future<Integer>) executorService.submit(new ReentranReadWriteLockCounterCallable(counter));
|
||||
Future<Integer> future2 = (Future<Integer>) executorService.submit(new ReentranReadWriteLockCounterCallable(counter));
|
||||
Future<Integer> future1 = (Future<Integer>) executorService.submit(new ReentranReadWriteLockCounterCallable(counter));
|
||||
Future<Integer> future2 = (Future<Integer>) executorService.submit(new ReentranReadWriteLockCounterCallable(counter));
|
||||
|
||||
assertThat(future2.get()).isEqualTo(2);
|
||||
assertThat(future1.get()).isEqualTo(1);
|
||||
// Just to make sure both are completed
|
||||
future1.get();
|
||||
future2.get();
|
||||
|
||||
assertThat(counter.getCounter()).isEqualTo(2);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
3
core-java-modules/core-java-date-operations/README.md
Normal file
3
core-java-modules/core-java-date-operations/README.md
Normal file
@ -0,0 +1,3 @@
|
||||
### Relevant Articles:
|
||||
- [Get the Current Date Prior to Java 8](https://www.baeldung.com/java-get-the-current-date-legacy)
|
||||
- [Skipping Weekends While Adding Days to LocalDate in Java 8](https://www.baeldung.com/java-localdate-add-days-skip-weekends)
|
@ -1,17 +1,38 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-date-operations</artifactId>
|
||||
<version>${project.parent.version}</version>
|
||||
<packaging>jar</packaging>
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-date-operations</artifactId>
|
||||
<version>${project.parent.version}</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-java</relativePath>
|
||||
</parent>
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>joda-time</groupId>
|
||||
<artifactId>joda-time</artifactId>
|
||||
<version>${joda-time.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.darwinsys</groupId>
|
||||
<artifactId>hirondelle-date4j</artifactId>
|
||||
<version>${hirondelle-date4j.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<properties>
|
||||
<joda-time.version>2.10</joda-time.version>
|
||||
<hirondelle-date4j.version>1.5.1</hirondelle-date4j.version>
|
||||
</properties>
|
||||
</project>
|
@ -0,0 +1,55 @@
|
||||
package com.baeldung.date.comparison;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.LocalDate;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import org.apache.commons.lang3.time.DateUtils;
|
||||
|
||||
import hirondelle.date4j.DateTime;
|
||||
|
||||
public class DateComparisonUtils {
|
||||
|
||||
public static boolean isSameDayUsingLocalDate(Date date1, Date date2) {
|
||||
LocalDate localDate1 = date1.toInstant()
|
||||
.atZone(ZoneId.systemDefault())
|
||||
.toLocalDate();
|
||||
LocalDate localDate2 = date2.toInstant()
|
||||
.atZone(ZoneId.systemDefault())
|
||||
.toLocalDate();
|
||||
return localDate1.isEqual(localDate2);
|
||||
}
|
||||
|
||||
public static boolean isSameDayUsingSimpleDateFormat(Date date1, Date date2) {
|
||||
SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
|
||||
return fmt.format(date1)
|
||||
.equals(fmt.format(date2));
|
||||
}
|
||||
|
||||
public static boolean isSameDayUsingCalendar(Date date1, Date date2) {
|
||||
Calendar calendar1 = Calendar.getInstance();
|
||||
calendar1.setTime(date1);
|
||||
Calendar calendar2 = Calendar.getInstance();
|
||||
calendar2.setTime(date2);
|
||||
return calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR) && calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH) && calendar1.get(Calendar.DAY_OF_MONTH) == calendar2.get(Calendar.DAY_OF_MONTH);
|
||||
}
|
||||
|
||||
public static boolean isSameDayUsingApacheCommons(Date date1, Date date2) {
|
||||
return DateUtils.isSameDay(date1, date2);
|
||||
}
|
||||
|
||||
public static boolean isSameDayUsingJoda(Date date1, Date date2) {
|
||||
org.joda.time.LocalDate localDate1 = new org.joda.time.LocalDate(date1);
|
||||
org.joda.time.LocalDate localDate2 = new org.joda.time.LocalDate(date2);
|
||||
return localDate1.equals(localDate2);
|
||||
}
|
||||
|
||||
public static boolean isSameDayUsingDate4j(Date date1, Date date2) {
|
||||
DateTime dateObject1 = DateTime.forInstant(date1.getTime(), TimeZone.getDefault());
|
||||
DateTime dateObject2 = DateTime.forInstant(date2.getTime(), TimeZone.getDefault());
|
||||
return dateObject1.isSameDayAs(dateObject2);
|
||||
}
|
||||
}
|
@ -0,0 +1,53 @@
|
||||
package com.baeldung.date.comparison;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Date;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class DateComparisonUtilsUnitTest {
|
||||
|
||||
private Date day1Morning = toDate(LocalDateTime.of(2019, 10, 19, 6, 30, 40));
|
||||
private Date day1Evening = toDate(LocalDateTime.of(2019, 10, 19, 18, 30, 50));
|
||||
private Date day2Morning = toDate(LocalDateTime.of(2019, 10, 20, 6, 30, 50));
|
||||
|
||||
private Date toDate(LocalDateTime localDateTime) {
|
||||
return Date.from(localDateTime.atZone(ZoneId.systemDefault())
|
||||
.toInstant());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDatesWithDifferentTime_whenIsSameDay_thenReturnsTrue() {
|
||||
assertTrue(DateComparisonUtils.isSameDayUsingLocalDate(day1Morning, day1Evening));
|
||||
assertTrue(DateComparisonUtils.isSameDayUsingSimpleDateFormat(day1Morning, day1Evening));
|
||||
assertTrue(DateComparisonUtils.isSameDayUsingCalendar(day1Morning, day1Evening));
|
||||
assertTrue(DateComparisonUtils.isSameDayUsingApacheCommons(day1Morning, day1Evening));
|
||||
assertTrue(DateComparisonUtils.isSameDayUsingJoda(day1Morning, day1Evening));
|
||||
assertTrue(DateComparisonUtils.isSameDayUsingDate4j(day1Morning, day1Evening));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDates_whenIsDifferentDay_thenReturnsFalse() {
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingLocalDate(day1Morning, day2Morning));
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingLocalDate(day1Evening, day2Morning));
|
||||
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingSimpleDateFormat(day1Morning, day2Morning));
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingSimpleDateFormat(day1Evening, day2Morning));
|
||||
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingCalendar(day1Morning, day2Morning));
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingCalendar(day1Evening, day2Morning));
|
||||
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingApacheCommons(day1Morning, day2Morning));
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingApacheCommons(day1Evening, day2Morning));
|
||||
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingJoda(day1Morning, day2Morning));
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingJoda(day1Evening, day2Morning));
|
||||
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingDate4j(day1Morning, day2Morning));
|
||||
assertFalse(DateComparisonUtils.isSameDayUsingDate4j(day1Evening, day2Morning));
|
||||
}
|
||||
}
|
@ -2,18 +2,16 @@ package com.baeldung.datetime.sql;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.datetime.sql.DateUtils;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.util.Date;
|
||||
import java.time.LocalDate;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class DateUtilsUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenCurrentDate_thenTodayIsReturned() {
|
||||
assertEquals(DateUtils.getNow(), new Date());
|
||||
assertEquals(DateUtils.getNow().toLocalDate(), LocalDate.now());
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
|
@ -7,15 +7,9 @@ import org.junit.Test;
|
||||
import com.baeldung.datetime.sql.TimeUtils;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.util.Date;
|
||||
|
||||
public class TimeUtilsUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenCurrentTime_thenNowIsReturned() {
|
||||
assertEquals(TimeUtils.getNow(), new Date());
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void givenTimeAsString_whenPatternIsNotRespected_thenExceptionIsThrown() {
|
||||
TimeUtils.getTime("10 11 12");
|
||||
|
@ -0,0 +1,22 @@
|
||||
package com.baeldung.timezone;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class ModifyDefaultTimezoneUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenDefaultTimezoneSet_thenDateTimezoneIsCorrect() {
|
||||
TimeZone.setDefault(TimeZone.getTimeZone("Portugal"));
|
||||
Date date = new Date();
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
assertEquals(calendar.getTimeZone(), TimeZone.getTimeZone("Portugal"));
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,34 @@
|
||||
package com.baeldung.timezone;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class ModifyTimezonePropertyUnitTest {
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
System.setProperty("user.timezone", "IST");
|
||||
TimeZone.setDefault(null);
|
||||
}
|
||||
|
||||
@After
|
||||
public void teardown() {
|
||||
System.clearProperty("user.timezone");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTimezonePropertySet_thenDateTimezoneIsCorrect() {
|
||||
Date date = new Date();
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
assertEquals(calendar.getTimeZone(), TimeZone.getTimeZone("IST"));
|
||||
}
|
||||
|
||||
}
|
@ -13,3 +13,4 @@ This module contains articles about the Date and Time API introduced with Java 8
|
||||
- [How to Get the Start and the End of a Day using Java](http://www.baeldung.com/java-day-start-end)
|
||||
- [Set the Time Zone of a Date in Java](https://www.baeldung.com/java-set-date-time-zone)
|
||||
- [Comparing Dates in Java](https://www.baeldung.com/java-comparing-dates)
|
||||
- [Generating Random Dates in Java](https://www.baeldung.com/java-random-dates)
|
||||
|
@ -17,3 +17,4 @@ This module contains articles about core java exceptions
|
||||
- [Common Java Exceptions](https://www.baeldung.com/java-common-exceptions)
|
||||
- [Throw Exception in Optional in Java 8](https://www.baeldung.com/java-optional-throw-exception)
|
||||
- [How to Find an Exception’s Root Cause in Java](https://www.baeldung.com/java-exception-root-cause)
|
||||
- [Is It a Bad Practice to Catch Throwable?](https://www.baeldung.com/java-catch-throwable-bad-practice)
|
||||
|
8
core-java-modules/core-java-io-2/.gitignore
vendored
8
core-java-modules/core-java-io-2/.gitignore
vendored
@ -1,3 +1,5 @@
|
||||
# Intellij
|
||||
.idea/
|
||||
*.iml
|
||||
0.*
|
||||
|
||||
# Files generated by integration tests
|
||||
# *.txt
|
||||
/temp
|
@ -1,4 +1,15 @@
|
||||
## Core Java IO
|
||||
|
||||
### Relevant Articles:
|
||||
This module contains articles about core Java input and output (IO)
|
||||
|
||||
### Relevant Articles:
|
||||
- [Create a File in a Specific Directory in Java](https://www.baeldung.com/java-create-file-in-directory)
|
||||
- [How to Read a Large File Efficiently with Java](https://www.baeldung.com/java-read-lines-large-file)
|
||||
- [Java – Write to File](https://www.baeldung.com/java-write-to-file)
|
||||
- [FileNotFoundException in Java](https://www.baeldung.com/java-filenotfound-exception)
|
||||
- [Delete the Contents of a File in Java](https://www.baeldung.com/java-delete-file-contents)
|
||||
- [List Files in a Directory in Java](https://www.baeldung.com/java-list-directory-files)
|
||||
- [Java – Append Data to a File](https://www.baeldung.com/java-append-to-file)
|
||||
- [How to Copy a File with Java](https://www.baeldung.com/java-copy-file)
|
||||
- [Create a Directory in Java](https://www.baeldung.com/java-create-directory)
|
||||
- [[<-- Prev]](/core-java-modules/core-java-io)
|
||||
|
@ -16,57 +16,16 @@
|
||||
<dependencies>
|
||||
<!-- utils -->
|
||||
<dependency>
|
||||
<groupId>net.sourceforge.collections</groupId>
|
||||
<artifactId>collections-generic</artifactId>
|
||||
<version>${collections-generic.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>${commons-collections4.version}</version>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
<!-- utils -->
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
<version>${commons-io.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-math3</artifactId>
|
||||
<version>${commons-math3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.decimal4j</groupId>
|
||||
<artifactId>decimal4j</artifactId>
|
||||
<version>${decimal4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.bouncycastle</groupId>
|
||||
<artifactId>bcprov-jdk15on</artifactId>
|
||||
<version>${bouncycastle.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.unix4j</groupId>
|
||||
<artifactId>unix4j-command</artifactId>
|
||||
<version>${unix4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.googlecode.grep4j</groupId>
|
||||
<artifactId>grep4j</artifactId>
|
||||
<version>${grep4j.version}</version>
|
||||
</dependency>
|
||||
<!-- web -->
|
||||
<!-- marshalling -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<!-- logging -->
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
@ -78,12 +37,6 @@
|
||||
<artifactId>log4j-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<!-- test scoped -->
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
@ -91,86 +44,6 @@
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.jayway.awaitility</groupId>
|
||||
<artifactId>awaitility</artifactId>
|
||||
<version>${avaitility.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-codec</groupId>
|
||||
<artifactId>commons-codec</artifactId>
|
||||
<version>${commons-codec.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.javamoney</groupId>
|
||||
<artifactId>moneta</artifactId>
|
||||
<version>${moneta.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.owasp.esapi</groupId>
|
||||
<artifactId>esapi</artifactId>
|
||||
<version>${esapi.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.sun.messaging.mq</groupId>
|
||||
<artifactId>fscontext</artifactId>
|
||||
<version>${fscontext.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.codepoetics</groupId>
|
||||
<artifactId>protonpack</artifactId>
|
||||
<version>${protonpack.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>one.util</groupId>
|
||||
<artifactId>streamex</artifactId>
|
||||
<version>${streamex.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.vavr</groupId>
|
||||
<artifactId>vavr</artifactId>
|
||||
<version>${vavr.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>${jmh-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${jmh-generator-annprocess.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hsqldb</groupId>
|
||||
<artifactId>hsqldb</artifactId>
|
||||
<version>${hsqldb.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.asynchttpclient/async-http-client -->
|
||||
<dependency>
|
||||
<groupId>org.asynchttpclient</groupId>
|
||||
<artifactId>async-http-client</artifactId>
|
||||
<version>${async-http-client.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.opencsv</groupId>
|
||||
<artifactId>opencsv</artifactId>
|
||||
<version>${opencsv.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!-- Mime Type Resolution Libraries -->
|
||||
<dependency>
|
||||
<groupId>org.apache.tika</groupId>
|
||||
<artifactId>tika-core</artifactId>
|
||||
<version>${tika.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.sf.jmimemagic</groupId>
|
||||
<artifactId>jmimemagic</artifactId>
|
||||
<version>${jmime-magic.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
@ -182,22 +55,6 @@
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>${exec-maven-plugin.version}</version>
|
||||
<configuration>
|
||||
<executable>java</executable>
|
||||
<mainClass>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</mainClass>
|
||||
<arguments>
|
||||
<argument>-Xmx300m</argument>
|
||||
<argument>-XX:+UseParallelGC</argument>
|
||||
<argument>-classpath</argument>
|
||||
<classpath />
|
||||
<argument>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</argument>
|
||||
</arguments>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-javadoc-plugin</artifactId>
|
||||
@ -210,70 +67,9 @@
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>integration</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
|
||||
<executions>
|
||||
<execution>
|
||||
<id>run-benchmarks</id>
|
||||
<!-- <phase>integration-test</phase> -->
|
||||
<phase>none</phase>
|
||||
<goals>
|
||||
<goal>exec</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<classpathScope>test</classpathScope>
|
||||
<executable>java</executable>
|
||||
<arguments>
|
||||
<argument>-classpath</argument>
|
||||
<classpath />
|
||||
<argument>org.openjdk.jmh.Main</argument>
|
||||
<argument>.*</argument>
|
||||
</arguments>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
<properties>
|
||||
|
||||
<!-- util -->
|
||||
<bouncycastle.version>1.55</bouncycastle.version>
|
||||
<commons-codec.version>1.10</commons-codec.version>
|
||||
<commons-math3.version>3.6.1</commons-math3.version>
|
||||
<decimal4j.version>1.0.3</decimal4j.version>
|
||||
<commons-collections4.version>4.1</commons-collections4.version>
|
||||
<collections-generic.version>4.01</collections-generic.version>
|
||||
<unix4j.version>0.4</unix4j.version>
|
||||
<grep4j.version>1.8.7</grep4j.version>
|
||||
<fscontext.version>4.6-b01</fscontext.version>
|
||||
<protonpack.version>1.13</protonpack.version>
|
||||
<streamex.version>0.6.5</streamex.version>
|
||||
<vavr.version>0.9.0</vavr.version>
|
||||
<opencsv.version>4.1</opencsv.version>
|
||||
<!-- testing -->
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<avaitility.version>1.7.0</avaitility.version>
|
||||
|
||||
<!-- maven plugins -->
|
||||
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
|
||||
<hsqldb.version>2.4.0</hsqldb.version>
|
||||
<esapi.version>2.1.0.1</esapi.version>
|
||||
<jmh-generator-annprocess.version>1.19</jmh-generator-annprocess.version>
|
||||
<async-http-client.version>2.4.5</async-http-client.version>
|
||||
<!-- Mime Type Libraries -->
|
||||
<tika.version>1.18</tika.version>
|
||||
<jmime-magic.version>0.1.5</jmime-magic.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.files;
|
||||
package com.baeldung.listfiles;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.file;
|
||||
package com.baeldung.appendtofile;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@ -22,9 +22,7 @@ import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.util.StreamUtils;
|
||||
|
||||
public class FilesManualTest {
|
||||
public class AppendToFileManualTest {
|
||||
|
||||
public static final String fileName = "src/main/resources/countries.properties";
|
||||
|
@ -1,11 +1,11 @@
|
||||
package com.baeldung.util;
|
||||
package com.baeldung.appendtofile;
|
||||
|
||||
import org.apache.commons.io.IOUtils;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.StringWriter;
|
||||
|
||||
import org.apache.commons.io.IOUtils;
|
||||
|
||||
public class StreamUtils {
|
||||
|
||||
public static String getStringFromInputStream(InputStream input) throws IOException {
|
@ -5,15 +5,27 @@ import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.BeforeClass;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class CreateFilesUnitTest {
|
||||
|
||||
@BeforeClass
|
||||
public static void clean() {
|
||||
File tempDirectory = new File(System.getProperty("java.io.tmpdir"));
|
||||
File file1 = new File(tempDirectory.getAbsolutePath() + "/testFile.txt");
|
||||
File file2 = new File(tempDirectory, "newFile.txt");
|
||||
File file3 = new File(tempDirectory.getAbsolutePath() + File.separator + "newFile2.txt");
|
||||
file1.delete();
|
||||
file2.delete();
|
||||
file3.delete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnExistingDirectory_whenCreatingAFileWithAbsolutePath_thenFileIsCreated() throws IOException {
|
||||
File tempDirectory = new File(System.getProperty("java.io.tmpdir"));
|
||||
File fileWithAbsolutePath = new File(tempDirectory.getAbsolutePath() + "/myDirectory/testFile.txt");
|
||||
File fileWithAbsolutePath = new File(tempDirectory.getAbsolutePath() + "/testFile.txt");
|
||||
|
||||
assertFalse(fileWithAbsolutePath.exists());
|
||||
|
||||
@ -25,7 +37,7 @@ public class CreateFilesUnitTest {
|
||||
@Test
|
||||
public void givenAnExistingDirectory_whenCreatingANewDirectoryAndFileWithRelativePath_thenFileIsCreated() throws IOException {
|
||||
File tempDirectory = new File(System.getProperty("java.io.tmpdir"));
|
||||
File fileWithRelativePath = new File(tempDirectory, "myDirectory/newFile.txt");
|
||||
File fileWithRelativePath = new File(tempDirectory, "newFile.txt");
|
||||
|
||||
assertFalse(fileWithRelativePath.exists());
|
||||
|
||||
@ -37,7 +49,7 @@ public class CreateFilesUnitTest {
|
||||
@Test
|
||||
public void whenCreatingAFileWithFileSeparator_thenFileIsCreated() throws IOException {
|
||||
File tempDirectory = new File(System.getProperty("java.io.tmpdir"));
|
||||
File newFile = new File(tempDirectory.getAbsolutePath() + File.separator + "newFile.txt");
|
||||
File newFile = new File(tempDirectory.getAbsolutePath() + File.separator + "newFile2.txt");
|
||||
|
||||
assertFalse(newFile.exists());
|
||||
|
||||
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.file;
|
||||
package com.baeldung.deletecontents;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
@ -20,8 +20,6 @@ import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.util.StreamUtils;
|
||||
|
||||
public class FilesClearDataUnitTest {
|
||||
|
||||
public static final String FILE_PATH = "src/test/resources/fileexample.txt";
|
@ -0,0 +1,16 @@
|
||||
package com.baeldung.deletecontents;
|
||||
|
||||
import org.apache.commons.io.IOUtils;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.StringWriter;
|
||||
|
||||
public class StreamUtils {
|
||||
|
||||
public static String getStringFromInputStream(InputStream input) throws IOException {
|
||||
StringWriter writer = new StringWriter();
|
||||
IOUtils.copy(input, writer, "UTF-8");
|
||||
return writer.toString();
|
||||
}
|
||||
}
|
@ -1,4 +1,4 @@
|
||||
package org.baeldung.core.exceptions;
|
||||
package com.baeldung.filenotfoundexception;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.file;
|
||||
package com.baeldung.listfiles;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
@ -8,7 +8,7 @@ import java.util.Set;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.files.ListFiles;
|
||||
import com.baeldung.listfiles.ListFiles;
|
||||
|
||||
public class ListFilesUnitTest {
|
||||
|
@ -1,4 +1,4 @@
|
||||
package org.baeldung.java;
|
||||
package com.baeldung.readlargefile;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
@ -16,7 +16,7 @@ import com.google.common.base.Charsets;
|
||||
import com.google.common.io.Files;
|
||||
|
||||
@Ignore("need large file for testing")
|
||||
public class JavaIoUnitTest {
|
||||
public class ReadLargeFileUnitTest {
|
||||
protected final Logger logger = LoggerFactory.getLogger(getClass());
|
||||
|
||||
// tests - iterate lines in a file
|
@ -1,4 +1,4 @@
|
||||
package org.baeldung.writetofile;
|
||||
package com.baeldung.writetofile;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
@ -1 +0,0 @@
|
||||
Hello, World!
|
@ -12,3 +12,5 @@ This module contains articles about core Java input/output(IO) APIs.
|
||||
- [Quick Use of FilenameFilter](https://www.baeldung.com/java-filename-filter)
|
||||
- [Guide to BufferedReader](https://www.baeldung.com/java-buffered-reader)
|
||||
- [Java Scanner](https://www.baeldung.com/java-scanner)
|
||||
- [Scanner nextLine() Method](https://www.baeldung.com/java-scanner-nextline)
|
||||
- [Java Scanner hasNext() vs. hasNextLine()](https://www.baeldung.com/java-scanner-hasnext-vs-hasnextline)
|
@ -14,6 +14,23 @@
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- logging -->
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>${log4j.version}</version>
|
||||
</dependency>
|
||||
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>log4j-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<!-- test scoped -->
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
|
@ -1,13 +1,13 @@
|
||||
package com.baeldung.scanner;
|
||||
package com.baeldung.scannernextline;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.Scanner;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class JavaScannerUnitTest {
|
||||
public class ScannerNextLineUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenReadingLines_thenCorrect() {
|
@ -7,3 +7,11 @@ This module contains articles about core Java input/output(IO) conversions.
|
||||
- [Java – Convert File to InputStream](https://www.baeldung.com/convert-file-to-input-stream)
|
||||
- [Java – Byte Array to Writer](https://www.baeldung.com/java-convert-byte-array-to-writer)
|
||||
- [Java InputStream to Byte Array and ByteBuffer](https://www.baeldung.com/convert-input-stream-to-array-of-bytes)
|
||||
- [Java – String to Reader](https://www.baeldung.com/java-convert-string-to-reader)
|
||||
- [Java – Byte Array to Reader](https://www.baeldung.com/java-convert-byte-array-to-reader)
|
||||
- [Java – File to Reader](https://www.baeldung.com/java-convert-file-to-reader)
|
||||
- [Java – InputStream to Reader](https://www.baeldung.com/java-convert-inputstream-to-reader)
|
||||
- [Java – Reader to String](https://www.baeldung.com/java-convert-reader-to-string)
|
||||
- [Java – Write a Reader to File](https://www.baeldung.com/java-write-reader-to-file)
|
||||
- [Java – Reader to Byte Array](https://www.baeldung.com/java-convert-reader-to-byte-array)
|
||||
- [Java – Reader to InputStream](https://www.baeldung.com/java-convert-reader-to-inputstream)
|
||||
|
@ -1,4 +1,4 @@
|
||||
package org.baeldung.java.io;
|
||||
package com.baeldung.readertox;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
@ -1,4 +1,4 @@
|
||||
package org.baeldung.java.io;
|
||||
package com.baeldung.xtoreader;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
@ -1,5 +0,0 @@
|
||||
0.*
|
||||
|
||||
# Files generated by integration tests
|
||||
# *.txt
|
||||
/temp
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user