Fixed conflicts

This commit is contained in:
amit2103 2019-11-25 00:24:40 +05:30
commit b787240f29
327 changed files with 4913 additions and 1361 deletions

View File

@ -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) - [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) - [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) - [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 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) - [How to Find the Kth Largest Element in Java](https://www.baeldung.com/java-kth-largest-element)

View File

@ -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) - [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) - [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) - [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) - [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) - [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) - More articles: [[<-- prev]](/algorithms-miscellaneous-2) [[next -->]](/algorithms-miscellaneous-4)

View File

@ -5,10 +5,10 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
### Relevant articles: ### Relevant articles:
- [Multi-Swarm Optimization Algorithm in Java](https://www.baeldung.com/java-multi-swarm-algorithm) - [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) - [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 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 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) - [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) - [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) - More articles: [[<-- prev]](/algorithms-miscellaneous-3) [[next -->]](/algorithms-miscellaneous-5)

View File

@ -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()));
}
}

View File

@ -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) - [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) - [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) - [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) - More articles: [[<-- prev]](/../algorithms-miscellaneous-4)

View 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)

View 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>

View File

@ -1,55 +1,55 @@
package com.baeldung.algorithms.binarysearch; package com.baeldung.algorithms.binarysearch;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
public class BinarySearch { public class BinarySearch {
public int runBinarySearchIteratively(int[] sortedArray, int key, int low, int high) { public int runBinarySearchIteratively(int[] sortedArray, int key, int low, int high) {
int index = Integer.MAX_VALUE; int index = Integer.MAX_VALUE;
while (low <= high) { while (low <= high) {
int mid = (low + high) / 2; int mid = (low + high) / 2;
if (sortedArray[mid] < key) { if (sortedArray[mid] < key) {
low = mid + 1; low = mid + 1;
} else if (sortedArray[mid] > key) { } else if (sortedArray[mid] > key) {
high = mid - 1; high = mid - 1;
} else if (sortedArray[mid] == key) { } else if (sortedArray[mid] == key) {
index = mid; index = mid;
break; break;
} }
} }
return index; return index;
} }
public int runBinarySearchRecursively(int[] sortedArray, int key, int low, int high) { public int runBinarySearchRecursively(int[] sortedArray, int key, int low, int high) {
int middle = (low + high) / 2; int middle = (low + high) / 2;
if (high < low) { if (high < low) {
return -1; return -1;
} }
if (key == sortedArray[middle]) { if (key == sortedArray[middle]) {
return middle; return middle;
} else if (key < sortedArray[middle]) { } else if (key < sortedArray[middle]) {
return runBinarySearchRecursively(sortedArray, key, low, middle - 1); return runBinarySearchRecursively(sortedArray, key, low, middle - 1);
} else { } else {
return runBinarySearchRecursively(sortedArray, key, middle + 1, high); return runBinarySearchRecursively(sortedArray, key, middle + 1, high);
} }
} }
public int runBinarySearchUsingJavaArrays(int[] sortedArray, Integer key) { public int runBinarySearchUsingJavaArrays(int[] sortedArray, Integer key) {
int index = Arrays.binarySearch(sortedArray, key); int index = Arrays.binarySearch(sortedArray, key);
return index; return index;
} }
public int runBinarySearchUsingJavaCollections(List<Integer> sortedList, Integer key) { public int runBinarySearchUsingJavaCollections(List<Integer> sortedList, Integer key) {
int index = Collections.binarySearch(sortedList, key); int index = Collections.binarySearch(sortedList, key);
return index; return index;
} }
} }

View File

@ -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;
}
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung.graph; package com.baeldung.algorithms.dfs;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;

View File

@ -1,194 +1,194 @@
package com.baeldung.algorithms.string.search; package com.baeldung.algorithms.textsearch;
import java.math.BigInteger; import java.math.BigInteger;
import java.util.Random; import java.util.Random;
public class StringSearchAlgorithms { public class TextSearchAlgorithms {
public static long getBiggerPrime(int m) { public static long getBiggerPrime(int m) {
BigInteger prime = BigInteger.probablePrime(getNumberOfBits(m) + 1, new Random()); BigInteger prime = BigInteger.probablePrime(getNumberOfBits(m) + 1, new Random());
return prime.longValue(); return prime.longValue();
} }
public static long getLowerPrime(long number) { public static long getLowerPrime(long number) {
BigInteger prime = BigInteger.probablePrime(getNumberOfBits(number) - 1, new Random()); BigInteger prime = BigInteger.probablePrime(getNumberOfBits(number) - 1, new Random());
return prime.longValue(); return prime.longValue();
} }
private static int getNumberOfBits(final int number) { private static int getNumberOfBits(final int number) {
return Integer.SIZE - Integer.numberOfLeadingZeros(number); return Integer.SIZE - Integer.numberOfLeadingZeros(number);
} }
private static int getNumberOfBits(final long number) { private static int getNumberOfBits(final long number) {
return Long.SIZE - Long.numberOfLeadingZeros(number); return Long.SIZE - Long.numberOfLeadingZeros(number);
} }
public static int simpleTextSearch(char[] pattern, char[] text) { public static int simpleTextSearch(char[] pattern, char[] text) {
int patternSize = pattern.length; int patternSize = pattern.length;
int textSize = text.length; int textSize = text.length;
int i = 0; int i = 0;
while ((i + patternSize) <= textSize) { while ((i + patternSize) <= textSize) {
int j = 0; int j = 0;
while (text[i + j] == pattern[j]) { while (text[i + j] == pattern[j]) {
j += 1; j += 1;
if (j >= patternSize) if (j >= patternSize)
return i; return i;
} }
i += 1; i += 1;
} }
return -1; return -1;
} }
public static int RabinKarpMethod(char[] pattern, char[] text) { public static int RabinKarpMethod(char[] pattern, char[] text) {
int patternSize = pattern.length; // m int patternSize = pattern.length; // m
int textSize = text.length; // n int textSize = text.length; // n
long prime = getBiggerPrime(patternSize); long prime = getBiggerPrime(patternSize);
long r = 1; long r = 1;
for (int i = 0; i < patternSize - 1; i++) { for (int i = 0; i < patternSize - 1; i++) {
r *= 2; r *= 2;
r = r % prime; r = r % prime;
} }
long[] t = new long[textSize]; long[] t = new long[textSize];
t[0] = 0; t[0] = 0;
long pfinger = 0; long pfinger = 0;
for (int j = 0; j < patternSize; j++) { for (int j = 0; j < patternSize; j++) {
t[0] = (2 * t[0] + text[j]) % prime; t[0] = (2 * t[0] + text[j]) % prime;
pfinger = (2 * pfinger + pattern[j]) % prime; pfinger = (2 * pfinger + pattern[j]) % prime;
} }
int i = 0; int i = 0;
boolean passed = false; boolean passed = false;
int diff = textSize - patternSize; int diff = textSize - patternSize;
for (i = 0; i <= diff; i++) { for (i = 0; i <= diff; i++) {
if (t[i] == pfinger) { if (t[i] == pfinger) {
passed = true; passed = true;
for (int k = 0; k < patternSize; k++) { for (int k = 0; k < patternSize; k++) {
if (text[i + k] != pattern[k]) { if (text[i + k] != pattern[k]) {
passed = false; passed = false;
break; break;
} }
} }
if (passed) { if (passed) {
return i; return i;
} }
} }
if (i < diff) { if (i < diff) {
long value = 2 * (t[i] - r * text[i]) + text[i + patternSize]; long value = 2 * (t[i] - r * text[i]) + text[i + patternSize];
t[i + 1] = ((value % prime) + prime) % prime; t[i + 1] = ((value % prime) + prime) % prime;
} }
} }
return -1; return -1;
} }
public static int KnuthMorrisPrattSearch(char[] pattern, char[] text) { public static int KnuthMorrisPrattSearch(char[] pattern, char[] text) {
int patternSize = pattern.length; // m int patternSize = pattern.length; // m
int textSize = text.length; // n int textSize = text.length; // n
int i = 0, j = 0; int i = 0, j = 0;
int[] shift = KnuthMorrisPrattShift(pattern); int[] shift = KnuthMorrisPrattShift(pattern);
while ((i + patternSize) <= textSize) { while ((i + patternSize) <= textSize) {
while (text[i + j] == pattern[j]) { while (text[i + j] == pattern[j]) {
j += 1; j += 1;
if (j >= patternSize) if (j >= patternSize)
return i; return i;
} }
if (j > 0) { if (j > 0) {
i += shift[j - 1]; i += shift[j - 1];
j = Math.max(j - shift[j - 1], 0); j = Math.max(j - shift[j - 1], 0);
} else { } else {
i++; i++;
j = 0; j = 0;
} }
} }
return -1; return -1;
} }
public static int[] KnuthMorrisPrattShift(char[] pattern) { public static int[] KnuthMorrisPrattShift(char[] pattern) {
int patternSize = pattern.length; int patternSize = pattern.length;
int[] shift = new int[patternSize]; int[] shift = new int[patternSize];
shift[0] = 1; shift[0] = 1;
int i = 1, j = 0; int i = 1, j = 0;
while ((i + j) < patternSize) { while ((i + j) < patternSize) {
if (pattern[i + j] == pattern[j]) { if (pattern[i + j] == pattern[j]) {
shift[i + j] = i; shift[i + j] = i;
j++; j++;
} else { } else {
if (j == 0) if (j == 0)
shift[i] = i + 1; shift[i] = i + 1;
if (j > 0) { if (j > 0) {
i = i + shift[j - 1]; i = i + shift[j - 1];
j = Math.max(j - shift[j - 1], 0); j = Math.max(j - shift[j - 1], 0);
} else { } else {
i = i + 1; i = i + 1;
j = 0; j = 0;
} }
} }
} }
return shift; return shift;
} }
public static int BoyerMooreHorspoolSimpleSearch(char[] pattern, char[] text) { public static int BoyerMooreHorspoolSimpleSearch(char[] pattern, char[] text) {
int patternSize = pattern.length; int patternSize = pattern.length;
int textSize = text.length; int textSize = text.length;
int i = 0, j = 0; int i = 0, j = 0;
while ((i + patternSize) <= textSize) { while ((i + patternSize) <= textSize) {
j = patternSize - 1; j = patternSize - 1;
while (text[i + j] == pattern[j]) { while (text[i + j] == pattern[j]) {
j--; j--;
if (j < 0) if (j < 0)
return i; return i;
} }
i++; i++;
} }
return -1; return -1;
} }
public static int BoyerMooreHorspoolSearch(char[] pattern, char[] text) { public static int BoyerMooreHorspoolSearch(char[] pattern, char[] text) {
int shift[] = new int[256]; int shift[] = new int[256];
for (int k = 0; k < 256; k++) { for (int k = 0; k < 256; k++) {
shift[k] = pattern.length; shift[k] = pattern.length;
} }
for (int k = 0; k < pattern.length - 1; k++) { for (int k = 0; k < pattern.length - 1; k++) {
shift[pattern[k]] = pattern.length - 1 - k; shift[pattern[k]] = pattern.length - 1 - k;
} }
int i = 0, j = 0; int i = 0, j = 0;
while ((i + pattern.length) <= text.length) { while ((i + pattern.length) <= text.length) {
j = pattern.length - 1; j = pattern.length - 1;
while (text[i + j] == pattern[j]) { while (text[i + j] == pattern[j]) {
j -= 1; j -= 1;
if (j < 0) if (j < 0)
return i; return i;
} }
i = i + shift[text[i + pattern.length - 1]]; i = i + shift[text[i + pattern.length - 1]];
} }
return -1; return -1;
} }
} }

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -1,43 +1,41 @@
package com.baeldung.algorithms.binarysearch; package com.baeldung.algorithms.binarysearch;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import org.junit.Assert;
import org.junit.Assert; import org.junit.Test;
import org.junit.Test;
import com.baeldung.algorithms.binarysearch.BinarySearch; public class BinarySearchUnitTest {
public class BinarySearchUnitTest { int[] sortedArray = { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 };
int key = 6;
int[] sortedArray = { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 }; int expectedIndexForSearchKey = 7;
int key = 6; int low = 0;
int expectedIndexForSearchKey = 7; int high = sortedArray.length - 1;
int low = 0; List<Integer> sortedList = Arrays.asList(0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9);
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() {
@Test BinarySearch binSearch = new BinarySearch();
public void givenASortedArrayOfIntegers_whenBinarySearchRunIterativelyForANumber_thenGetIndexOfTheNumber() { Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchIteratively(sortedArray, key, low, high));
BinarySearch binSearch = new BinarySearch(); }
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchIteratively(sortedArray, key, low, high));
} @Test
public void givenASortedArrayOfIntegers_whenBinarySearchRunRecursivelyForANumber_thenGetIndexOfTheNumber() {
@Test BinarySearch binSearch = new BinarySearch();
public void givenASortedArrayOfIntegers_whenBinarySearchRunRecursivelyForANumber_thenGetIndexOfTheNumber() { Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchRecursively(sortedArray, key, low, high));
BinarySearch binSearch = new BinarySearch(); }
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchRecursively(sortedArray, key, low, high));
} @Test
public void givenASortedArrayOfIntegers_whenBinarySearchRunUsingArraysClassStaticMethodForANumber_thenGetIndexOfTheNumber() {
@Test BinarySearch binSearch = new BinarySearch();
public void givenASortedArrayOfIntegers_whenBinarySearchRunUsingArraysClassStaticMethodForANumber_thenGetIndexOfTheNumber() { Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaArrays(sortedArray, key));
BinarySearch binSearch = new BinarySearch(); }
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaArrays(sortedArray, key));
} @Test
public void givenASortedListOfIntegers_whenBinarySearchRunUsingCollectionsClassStaticMethodForANumber_thenGetIndexOfTheNumber() {
@Test BinarySearch binSearch = new BinarySearch();
public void givenASortedListOfIntegers_whenBinarySearchRunUsingCollectionsClassStaticMethodForANumber_thenGetIndexOfTheNumber() { Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaCollections(sortedList, key));
BinarySearch binSearch = new BinarySearch(); }
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaCollections(sortedList, key));
} }
}

View File

@ -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;
}
}

View File

@ -1,7 +1,8 @@
package com.baeldung.graph; package com.baeldung.algorithms.dfs;
import java.util.List; import java.util.List;
import com.baeldung.algorithms.dfs.Graph;
import org.junit.Test; import org.junit.Test;
public class GraphUnitTest { public class GraphUnitTest {

View File

@ -1,10 +1,10 @@
package com.baeldung.algorithms.interpolationsearch; package com.baeldung.algorithms.interpolationsearch;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class InterpolationSearchUnitTest { public class InterpolationSearchUnitTest {
private int[] myData; private int[] myData;

View File

@ -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()));
}
}

View File

@ -15,7 +15,7 @@ public class LocalDbCreationRule extends ExternalResource {
@Override @Override
protected void before() throws Exception { protected void before() throws Exception {
String port = "8000"; String port = "8000";
this.server = ServerRunner.createServerFromCommandLineArgs(new String[]{"-inMemory", "-port", port}); this.server = ServerRunner.createServerFromCommandLineArgs(new String[]{"-inMemory","-sharedDb" ,"-port", port});
server.start(); server.start();
} }

View File

@ -7,3 +7,4 @@ This module contains articles about automatic code generation
- [Introduction to AutoValue](https://www.baeldung.com/introduction-to-autovalue) - [Introduction to AutoValue](https://www.baeldung.com/introduction-to-autovalue)
- [Introduction to AutoFactory](https://www.baeldung.com/autofactory) - [Introduction to AutoFactory](https://www.baeldung.com/autofactory)
- [Google AutoService](https://www.baeldung.com/google-autoservice) - [Google AutoService](https://www.baeldung.com/google-autoservice)
- [Defensive Copies for Collections Using AutoValue](https://www.baeldung.com/autovalue-defensive-copies)

View File

@ -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) - [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) - [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) - [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) - [[<-- Prev]](/core-java-modules/core-java-collections-list-2)

View File

@ -14,11 +14,18 @@
<relativePath>../../parent-java</relativePath> <relativePath>../../parent-java</relativePath>
</parent> </parent>
<dependencies>
</dependencies>
<build> <build>
<finalName>core-java-concurrency-advanced-3</finalName> <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> <resources>
<resource> <resource>
<directory>src/main/resources</directory> <directory>src/main/resources</directory>
@ -28,6 +35,8 @@
</build> </build>
<properties> <properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties> </properties>
</project> </project>

View File

@ -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");
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.commonissues;
class Counter {
private int counter = 0;
public void increment() {
counter++;
}
public int getValue() {
return counter;
}
}

View File

@ -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();
}
}
}

View File

@ -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();
}
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View 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)

View File

@ -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) - [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) - [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) - [Comparing Dates in Java](https://www.baeldung.com/java-comparing-dates)
- [Generating Random Dates in Java](https://www.baeldung.com/java-random-dates)

View File

@ -17,3 +17,4 @@ This module contains articles about core java exceptions
- [Common Java Exceptions](https://www.baeldung.com/java-common-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) - [Throw Exception in Optional in Java 8](https://www.baeldung.com/java-optional-throw-exception)
- [How to Find an Exceptions Root Cause in Java](https://www.baeldung.com/java-exception-root-cause) - [How to Find an Exceptions 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)

View File

@ -5,4 +5,5 @@ This module contains articles about core features in the Java language
### Relevant Articles: ### Relevant Articles:
- [Java Primitives versus Objects](https://www.baeldung.com/java-primitives-vs-objects) - [Java Primitives versus Objects](https://www.baeldung.com/java-primitives-vs-objects)
- [Command-Line Arguments in Java](https://www.baeldung.com/java-command-line-arguments) - [Command-Line Arguments in Java](https://www.baeldung.com/java-command-line-arguments)
- [What is a POJO Class?](https://www.baeldung.com/java-pojo-class)
- [[<-- Prev]](/core-java-modules/core-java-lang) - [[<-- Prev]](/core-java-modules/core-java-lang)

View File

@ -6,3 +6,4 @@
- [Java 8 Math New Methods](https://www.baeldung.com/java-8-math) - [Java 8 Math New Methods](https://www.baeldung.com/java-8-math)
- [Java 8 Unsigned Arithmetic Support](https://www.baeldung.com/java-unsigned-arithmetic) - [Java 8 Unsigned Arithmetic Support](https://www.baeldung.com/java-unsigned-arithmetic)
- [How to Separate Double into Integer and Decimal Parts](https://www.baeldung.com/java-separate-double-into-integer-decimal-parts) - [How to Separate Double into Integer and Decimal Parts](https://www.baeldung.com/java-separate-double-into-integer-decimal-parts)
- [The strictfp Keyword in Java](https://www.baeldung.com/java-strictfp)

View File

@ -0,0 +1,50 @@
package com.baeldung.calculator.basic;
import java.util.InputMismatchException;
import java.util.Scanner;
public class BasicCalculatorIfElse {
public static void main(String[] args) {
System.out.println("---------------------------------- \n" + "Welcome to Basic Calculator \n" + "----------------------------------");
System.out.println("Following operations are supported : \n" + "1. Addition (+) \n" + "2. Subtraction (-) \n" + "3. Multiplication (* OR x) \n" + "4. Division (/) \n");
Scanner scanner = new Scanner(System.in);
try {
System.out.println("Enter an operator: (+ OR - OR * OR /) ");
char operation = scanner.next()
.charAt(0);
if (!(operation == '+' || operation == '-' || operation == '*' || operation == 'x' || operation == '/')) {
System.err.println("Invalid Operator. Please use only + or - or * or /");
}
System.out.println("Enter First Number: ");
double num1 = scanner.nextDouble();
System.out.println("Enter Second Number: ");
double num2 = scanner.nextDouble();
if (operation == '/' && num2 == 0.0) {
System.err.println("Second Number cannot be zero for Division operation.");
}
if (operation == '+') {
System.out.println(num1 + " + " + num2 + " = " + (num1 + num2));
} else if (operation == '-') {
System.out.println(num1 + " - " + num2 + " = " + (num1 - num2));
} else if (operation == '*' || operation == 'x') {
System.out.println(num1 + " x " + num2 + " = " + (num1 * num2));
} else if (operation == '/') {
System.out.println(num1 + " / " + num2 + " = " + (num1 / num2));
} else {
System.err.println("Invalid Operator Specified.");
}
} catch (InputMismatchException exc) {
System.err.println(exc.getMessage());
} finally {
scanner.close();
}
}
}

View File

@ -0,0 +1,58 @@
package com.baeldung.calculator.basic;
import java.util.InputMismatchException;
import java.util.Scanner;
public class BasicCalculatorSwitchCase {
public static void main(String[] args) {
System.out.println("---------------------------------- \n" + "Welcome to Basic Calculator \n" + "----------------------------------");
System.out.println("Following operations are supported : \n" + "1. Addition (+) \n" + "2. Subtraction (-) \n" + "3. Multiplication (* OR x) \n" + "4. Division (/) \n");
Scanner scanner = new Scanner(System.in);
try {
System.out.println("Enter an operator: (+ OR - OR * OR /) ");
char operation = scanner.next()
.charAt(0);
if (!(operation == '+' || operation == '-' || operation == '*' || operation == 'x' || operation == '/')) {
System.err.println("Invalid Operator. Please use only + or - or * or /");
}
System.out.println("Enter First Number: ");
double num1 = scanner.nextDouble();
System.out.println("Enter Second Number: ");
double num2 = scanner.nextDouble();
if (operation == '/' && num2 == 0.0) {
System.err.println("Second Number cannot be zero for Division operation.");
}
switch (operation) {
case '+':
System.out.println(num1 + " + " + num2 + " = " + (num1 + num2));
break;
case '-':
System.out.println(num1 + " - " + num2 + " = " + (num1 - num2));
break;
case '*':
System.out.println(num1 + " x " + num2 + " = " + (num1 * num2));
break;
case 'x':
System.out.println(num1 + " x " + num2 + " = " + (num1 * num2));
break;
case '/':
System.out.println(num1 + " / " + num2 + " = " + (num1 / num2));
break;
default:
System.err.println("Invalid Operator Specified.");
break;
}
} catch (InputMismatchException exc) {
System.err.println(exc.getMessage());
} finally {
scanner.close();
}
}
}

View File

@ -0,0 +1,70 @@
package com.baeldung.overflow;
import java.math.BigInteger;
public class Overflow {
public static void showIntegerOverflow() {
int value = Integer.MAX_VALUE-1;
for(int i = 0; i < 4; i++, value++) {
System.out.println(value);
}
}
public static void noOverflowWithBigInteger() {
BigInteger largeValue = new BigInteger(Integer.MAX_VALUE + "");
for(int i = 0; i < 4; i++) {
System.out.println(largeValue);
largeValue = largeValue.add(BigInteger.ONE);
}
}
public static void exceptionWithAddExact() {
int value = Integer.MAX_VALUE-1;
for(int i = 0; i < 4; i++) {
System.out.println(value);
value = Math.addExact(value, 1);
}
}
public static int addExact(int x, int y) {
int r = x + y;
if (((x ^ r) & (y ^ r)) < 0) {
throw new ArithmeticException("int overflow");
}
return r;
}
public static void demonstrateUnderflow() {
for(int i = 1073; i <= 1076; i++) {
System.out.println("2^" + i + " = " + Math.pow(2, -i));
}
}
public static double powExact(double base, double exponent)
{
if(base == 0.0) {
return 0.0;
}
double result = Math.pow(base, exponent);
if(result == Double.POSITIVE_INFINITY ) {
throw new ArithmeticException("Double overflow resulting in POSITIVE_INFINITY");
} else if(result == Double.NEGATIVE_INFINITY) {
throw new ArithmeticException("Double overflow resulting in NEGATIVE_INFINITY");
} else if(Double.compare(-0.0f, result) == 0) {
throw new ArithmeticException("Double overflow resulting in negative zero");
} else if(Double.compare(+0.0f, result) == 0) {
throw new ArithmeticException("Double overflow resulting in positive zero");
}
return result;
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.math;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class OverflowUnitTest {
@Test
public void positive_and_negative_zero_are_not_always_equal() {
double a = +0f;
double b = -0f;
assertTrue(a == b);
assertTrue(1/a == Double.POSITIVE_INFINITY);
assertTrue(1/b == Double.NEGATIVE_INFINITY);
assertTrue(1/a != 1/b);
}
}

View File

@ -8,4 +8,5 @@ This module contains articles about the Stream API in Java.
- [The Difference Between Collection.stream().forEach() and Collection.forEach()](https://www.baeldung.com/java-collection-stream-foreach) - [The Difference Between Collection.stream().forEach() and Collection.forEach()](https://www.baeldung.com/java-collection-stream-foreach)
- [Guide to Java 8s Collectors](https://www.baeldung.com/java-8-collectors) - [Guide to Java 8s Collectors](https://www.baeldung.com/java-8-collectors)
- [Primitive Type Streams in Java 8](https://www.baeldung.com/java-8-primitive-streams) - [Primitive Type Streams in Java 8](https://www.baeldung.com/java-8-primitive-streams)
- More articles: [[<-- prev>]](/../core-java-streams-2) - [Debugging Java 8 Streams with IntelliJ](https://www.baeldung.com/intellij-debugging-java-streams)
- More articles: [[<-- prev>]](/../core-java-streams-2)

View File

@ -58,7 +58,7 @@
</build> </build>
<properties> <properties>
<commons-lang3.version>3.8.1</commons-lang3.version> <commons-lang3.version>3.9</commons-lang3.version>
<assertj.version>3.6.1</assertj.version> <assertj.version>3.6.1</assertj.version>
<commons-codec.version>1.10</commons-codec.version> <commons-codec.version>1.10</commons-codec.version>
</properties> </properties>

View File

@ -1,6 +1,9 @@
package com.baeldung.isnumeric; package com.baeldung.isnumeric;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.BenchmarkMode;
@ -14,6 +17,8 @@ import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder; import org.openjdk.jmh.runner.options.OptionsBuilder;
public class Benchmarking { public class Benchmarking {
private static final TestMode MODE = TestMode.DIVERS;
public static void main(String[] args) throws RunnerException { public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder().include(Benchmarking.class.getSimpleName()) Options opt = new OptionsBuilder().include(Benchmarking.class.getSimpleName())
.forks(1) .forks(1)
@ -22,52 +27,89 @@ public class Benchmarking {
new Runner(opt).run(); new Runner(opt).run();
} }
private static final IsNumeric subject = new IsNumeric();
@State(Scope.Thread) @State(Scope.Thread)
public static class ExecutionPlan { public static class ExecutionPlan {
public String number = Integer.toString(Integer.MAX_VALUE); private final Map<String, Boolean> testPlan = testPlan();
public boolean isNumber = false;
public IsNumeric isNumeric = new IsNumeric(); void validate(Function<String, Boolean> functionUnderTest) {
testPlan.forEach((key, value) -> {
Boolean result = functionUnderTest.apply(key);
assertEquals(value, result, key);
});
}
private void assertEquals(Boolean expectedResult, Boolean result, String input) {
if (result != expectedResult) {
throw new IllegalStateException("The output does not match the expected output, for input: " + input);
}
}
private Map<String, Boolean> testPlan() {
HashMap<String, Boolean> plan = new HashMap<>();
plan.put(Integer.toString(Integer.MAX_VALUE), true);
if (MODE == TestMode.SIMPLE) {
return plan;
}
plan.put("x0", false);
plan.put("0..005", false);
plan.put("--11", false);
plan.put("test", false);
plan.put(null, false);
for (int i = 0; i < 94; i++) {
plan.put(Integer.toString(i), true);
}
return plan;
}
} }
@Benchmark @Benchmark
@BenchmarkMode(Mode.AverageTime) @BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS) @OutputTimeUnit(TimeUnit.NANOSECONDS)
public void usingCoreJava(ExecutionPlan plan) { public void usingCoreJava(ExecutionPlan plan) {
plan.isNumber = plan.isNumeric.usingCoreJava(plan.number); plan.validate(subject::usingCoreJava);
} }
@Benchmark @Benchmark
@BenchmarkMode(Mode.AverageTime) @BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS) @OutputTimeUnit(TimeUnit.NANOSECONDS)
public void usingRegularExpressions(ExecutionPlan plan) { public void usingRegularExpressions(ExecutionPlan plan) {
plan.isNumber = plan.isNumeric.usingRegularExpressions(plan.number); plan.validate(subject::usingPreCompiledRegularExpressions);
} }
@Benchmark @Benchmark
@BenchmarkMode(Mode.AverageTime) @BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS) @OutputTimeUnit(TimeUnit.NANOSECONDS)
public void usingNumberUtils_isCreatable(ExecutionPlan plan) { public void usingNumberUtils_isCreatable(ExecutionPlan plan) {
plan.isNumber = plan.isNumeric.usingNumberUtils_isCreatable(plan.number); plan.validate(subject::usingNumberUtils_isCreatable);
} }
@Benchmark @Benchmark
@BenchmarkMode(Mode.AverageTime) @BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS) @OutputTimeUnit(TimeUnit.NANOSECONDS)
public void usingNumberUtils_isParsable(ExecutionPlan plan) { public void usingNumberUtils_isParsable(ExecutionPlan plan) {
plan.isNumber = plan.isNumeric.usingNumberUtils_isParsable(plan.number); plan.validate(subject::usingNumberUtils_isParsable);
} }
@Benchmark @Benchmark
@BenchmarkMode(Mode.AverageTime) @BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS) @OutputTimeUnit(TimeUnit.NANOSECONDS)
public void usingStringUtils_isNumeric(ExecutionPlan plan) { public void usingStringUtils_isNumeric(ExecutionPlan plan) {
plan.isNumber = plan.isNumeric.usingStringUtils_isNumeric(plan.number); plan.validate(subject::usingStringUtils_isNumeric);
} }
@Benchmark @Benchmark
@BenchmarkMode(Mode.AverageTime) @BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS) @OutputTimeUnit(TimeUnit.NANOSECONDS)
public void usingStringUtils_isNumericSpace(ExecutionPlan plan) { public void usingStringUtils_isNumericSpace(ExecutionPlan plan) {
plan.isNumber = plan.isNumeric.usingStringUtils_isNumericSpace(plan.number); plan.validate(subject::usingStringUtils_isNumericSpace);
}
private enum TestMode {
SIMPLE, DIVERS
} }
} }

View File

@ -1,18 +0,0 @@
package com.baeldung.isnumeric;
import java.util.Scanner;
public class CheckIntegerInput {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
System.out.println("Enter an integer : ");
if (scanner.hasNextInt()) {
System.out.println("You entered : " + scanner.nextInt());
} else {
System.out.println("The input is not an integer");
}
}
}
}

View File

@ -1,20 +1,33 @@
package com.baeldung.isnumeric; package com.baeldung.isnumeric;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils; import org.apache.commons.lang3.math.NumberUtils;
public class IsNumeric { public class IsNumeric {
private final Pattern pattern = Pattern.compile("-?\\d+(\\.\\d+)?");
public boolean usingCoreJava(String strNum) { public boolean usingCoreJava(String strNum) {
if (strNum == null) {
return false;
}
try { try {
Double.parseDouble(strNum); Double.parseDouble(strNum);
} catch (NumberFormatException | NullPointerException nfe) { } catch (NumberFormatException nfe) {
return false; return false;
} }
return true; return true;
} }
public boolean usingRegularExpressions(String strNum) { public boolean usingPreCompiledRegularExpressions(String strNum) {
return strNum.matches("-?\\d+(\\.\\d+)?"); if (strNum == null) {
return false;
}
return pattern.matcher(strNum)
.matches();
} }
public boolean usingNumberUtils_isCreatable(String strNum) { public boolean usingNumberUtils_isCreatable(String strNum) {

View File

@ -13,8 +13,8 @@ public class IsNumericDriver {
boolean res = isNumeric.usingCoreJava("1001"); boolean res = isNumeric.usingCoreJava("1001");
LOG.info("Using Core Java : " + res); LOG.info("Using Core Java : " + res);
res = isNumeric.usingRegularExpressions("1001"); res = isNumeric.usingPreCompiledRegularExpressions("1001");
LOG.info("Using Regular Expressions : " + res); LOG.info("Using Pre-compiled Regular Expressions : " + res);
res = isNumeric.usingNumberUtils_isCreatable("1001"); res = isNumeric.usingNumberUtils_isCreatable("1001");
LOG.info("Using NumberUtils.isCreatable : " + res); LOG.info("Using NumberUtils.isCreatable : " + res);

View File

@ -6,9 +6,13 @@ import org.junit.Test;
public class CoreJavaIsNumericUnitTest { public class CoreJavaIsNumericUnitTest {
public static boolean isNumeric(String strNum) { public static boolean isNumeric(String strNum) {
if (strNum == null) {
return false;
}
try { try {
double d = Double.parseDouble(strNum); Double.parseDouble(strNum);
} catch (NumberFormatException | NullPointerException nfe) { } catch (NumberFormatException nfe) {
return false; return false;
} }
return true; return true;

View File

@ -2,11 +2,19 @@ package com.baeldung.isnumeric;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import java.util.regex.Pattern;
import org.junit.Test; import org.junit.Test;
public class RegularExpressionsUnitTest { public class RegularExpressionsUnitTest {
public static boolean isNumeric(String strNum) { private final Pattern pattern = Pattern.compile("-?\\d+(\\.\\d+)?");
return strNum.matches("-?\\d+(\\.\\d+)?");
public boolean isNumeric(String strNum) {
if (strNum == null) {
return false;
}
return pattern.matcher(strNum)
.matches();
} }
@Test @Test
@ -17,6 +25,7 @@ public class RegularExpressionsUnitTest {
assertThat(isNumeric("-200")).isTrue(); assertThat(isNumeric("-200")).isTrue();
// Invalid Numbers // Invalid Numbers
assertThat(isNumeric(null)).isFalse();
assertThat(isNumeric("abc")).isFalse(); assertThat(isNumeric("abc")).isFalse();
} }
} }

View File

@ -6,4 +6,3 @@ This module contains articles about data structures in Java
- [The Trie Data Structure in Java](https://www.baeldung.com/trie-java) - [The Trie Data Structure in Java](https://www.baeldung.com/trie-java)
- [Implementing a Binary Tree in Java](https://www.baeldung.com/java-binary-tree) - [Implementing a Binary Tree in Java](https://www.baeldung.com/java-binary-tree)
- [Depth First Search in Java](https://www.baeldung.com/java-depth-first-search)

View File

@ -14,14 +14,6 @@
<dependencies> <dependencies>
<!-- marshalling -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- YAML --> <!-- YAML -->
<dependency> <dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId> <groupId>com.fasterxml.jackson.dataformat</groupId>

View File

@ -0,0 +1,11 @@
## Jackson Annotations
This module contains articles about Jackson annotations.
### Relevant Articles:
- [Guide to @JsonFormat in Jackson](https://www.baeldung.com/jackson-jsonformat)
- [More Jackson Annotations](https://www.baeldung.com/jackson-advanced-annotations)
- [Jackson Annotation Examples](https://www.baeldung.com/jackson-annotations)
- [Jackson Bidirectional Relationships](https://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion)
- [Jackson Change Name of Field](https://www.baeldung.com/jackson-name-of-property)
- [Jackson Ignore Properties on Marshalling](https://www.baeldung.com/jackson-ignore-properties-on-serialization)

View File

@ -0,0 +1,60 @@
<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>jackson-annotations</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>jackson-annotations</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-jsonSchema</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-path</artifactId>
<version>${rest-assured.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>jackson-annotations</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<properties>
<assertj.version>3.11.0</assertj.version>
<rest-assured.version>3.1.1</rest-assured.version>
</properties>
</project>

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.bidirection; package com.baeldung.jackson.annotation.bidirection;
import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators; import com.fasterxml.jackson.annotation.ObjectIdGenerators;

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.bidirection; package com.baeldung.jackson.annotation.bidirection;
public class ItemWithIgnore { public class ItemWithIgnore {
public int id; public int id;

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.bidirection; package com.baeldung.jackson.annotation.bidirection;
import com.fasterxml.jackson.annotation.JsonManagedReference; import com.fasterxml.jackson.annotation.JsonManagedReference;

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.bidirection; package com.baeldung.jackson.annotation.bidirection;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.bidirection; package com.baeldung.jackson.annotation.bidirection;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.bidirection; package com.baeldung.jackson.annotation.bidirection;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.date; package com.baeldung.jackson.annotation.date;
import java.io.IOException; import java.io.IOException;
import java.text.ParseException; import java.text.ParseException;

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.date; package com.baeldung.jackson.annotation.date;
import java.io.IOException; import java.io.IOException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.date; package com.baeldung.jackson.annotation.date;
import java.util.Date; import java.util.Date;

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.date; package com.baeldung.jackson.annotation.date;
import java.util.Date; import java.util.Date;

View File

@ -0,0 +1,41 @@
package com.baeldung.jackson.annotation.deserialization;
import java.io.IOException;
import com.baeldung.jackson.annotation.dtos.ItemWithSerializer;
import com.baeldung.jackson.annotation.dtos.User;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.node.IntNode;
public class ItemDeserializerOnClass extends StdDeserializer<ItemWithSerializer> {
private static final long serialVersionUID = 5579141241817332594L;
public ItemDeserializerOnClass() {
this(null);
}
public ItemDeserializerOnClass(final Class<?> vc) {
super(vc);
}
/**
* {"id":1,"itemNr":"theItem","owner":2}
*/
@Override
public ItemWithSerializer deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException {
final JsonNode node = jp.getCodec()
.readTree(jp);
final int id = (Integer) ((IntNode) node.get("id")).numberValue();
final String itemName = node.get("itemName")
.asText();
final int userId = (Integer) ((IntNode) node.get("owner")).numberValue();
return new ItemWithSerializer(id, itemName, new User(userId, null));
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.jackson.annotation.dtos;
public class Item {
public int id;
public String itemName;
public User owner;
public Item() {
super();
}
public Item(final int id, final String itemName, final User owner) {
this.id = id;
this.itemName = itemName;
this.owner = owner;
}
// API
public int getId() {
return id;
}
public String getItemName() {
return itemName;
}
public User getOwner() {
return owner;
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.jackson.annotation.dtos;
import com.baeldung.jackson.annotation.deserialization.ItemDeserializerOnClass;
import com.baeldung.jackson.annotation.serialization.ItemSerializerOnClass;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@JsonSerialize(using = ItemSerializerOnClass.class)
@JsonDeserialize(using = ItemDeserializerOnClass.class)
public class ItemWithSerializer {
public final int id;
public final String itemName;
public final User owner;
public ItemWithSerializer(final int id, final String itemName, final User owner) {
this.id = id;
this.itemName = itemName;
this.owner = owner;
}
// API
public int getId() {
return id;
}
public String getItemName() {
return itemName;
}
public User getOwner() {
return owner;
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.jackson.annotation.dtos;
public class User {
public int id;
public String name;
public User() {
super();
}
public User(final int id, final String name) {
this.id = id;
this.name = name;
}
// API
public int getId() {
return id;
}
public String getName() {
return name;
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.jackson.annotation.dtos.withEnum;
import com.fasterxml.jackson.annotation.JsonValue;
public enum DistanceEnumWithValue {
KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001);
private String unit;
private final double meters;
private DistanceEnumWithValue(String unit, double meters) {
this.unit = unit;
this.meters = meters;
}
@JsonValue
public double getMeters() {
return meters;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.exception; package com.baeldung.jackson.annotation.exception;
import com.fasterxml.jackson.annotation.JsonRootName; import com.fasterxml.jackson.annotation.JsonRootName;

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.exception; package com.baeldung.jackson.annotation.exception;
import com.fasterxml.jackson.annotation.JsonRootName; import com.fasterxml.jackson.annotation.JsonRootName;

View File

@ -0,0 +1,36 @@
package com.baeldung.jackson.annotation.jsonview;
import com.fasterxml.jackson.annotation.JsonView;
public class Item {
@JsonView(Views.Public.class)
public int id;
@JsonView(Views.Public.class)
public String itemName;
@JsonView(Views.Internal.class)
public String ownerName;
public Item() {
super();
}
public Item(final int id, final String itemName, final String ownerName) {
this.id = id;
this.itemName = itemName;
this.ownerName = ownerName;
}
public int getId() {
return id;
}
public String getItemName() {
return itemName;
}
public String getOwnerName() {
return ownerName;
}
}

View File

@ -0,0 +1,9 @@
package com.baeldung.jackson.annotation.jsonview;
public class Views {
public static class Public {
}
public static class Internal extends Public {
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.jackson.annotation.serialization;
import java.io.IOException;
import com.baeldung.jackson.annotation.dtos.Item;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
public class ItemSerializer extends StdSerializer<Item> {
private static final long serialVersionUID = 6739170890621978901L;
public ItemSerializer() {
this(null);
}
public ItemSerializer(final Class<Item> t) {
super(t);
}
@Override
public final void serialize(final Item value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException {
jgen.writeStartObject();
jgen.writeNumberField("id", value.id);
jgen.writeStringField("itemName", value.itemName);
jgen.writeNumberField("owner", value.owner.id);
jgen.writeEndObject();
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.jackson.annotation.serialization;
import java.io.IOException;
import com.baeldung.jackson.annotation.dtos.ItemWithSerializer;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
public class ItemSerializerOnClass extends StdSerializer<ItemWithSerializer> {
private static final long serialVersionUID = -1760959597313610409L;
public ItemSerializerOnClass() {
this(null);
}
public ItemSerializerOnClass(final Class<ItemWithSerializer> t) {
super(t);
}
@Override
public final void serialize(final ItemWithSerializer value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException {
jgen.writeStartObject();
jgen.writeNumberField("id", value.id);
jgen.writeStringField("itemName", value.itemName);
jgen.writeNumberField("owner", value.owner.id);
jgen.writeEndObject();
}
}

Some files were not shown because too many files have changed in this diff Show More