Fixed conflicts
This commit is contained in:
commit
b787240f29
|
@ -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)
|
||||
|
|
|
@ -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)
|
|
@ -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>
|
|
@ -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,9 +1,9 @@
|
|||
package com.baeldung.algorithms.string.search;
|
||||
package com.baeldung.algorithms.textsearch;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.Random;
|
||||
|
||||
public class StringSearchAlgorithms {
|
||||
public class TextSearchAlgorithms {
|
||||
public static long getBiggerPrime(int m) {
|
||||
BigInteger prime = BigInteger.probablePrime(getNumberOfBits(m) + 1, new Random());
|
||||
return prime.longValue();
|
|
@ -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>
|
|
@ -2,10 +2,8 @@ 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 {
|
||||
|
|
@ -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)
|
||||
|
|
|
@ -14,11 +14,18 @@
|
|||
<relativePath>../../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
</dependencies>
|
||||
|
||||
<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>
|
||||
|
@ -28,6 +35,8 @@
|
|||
</build>
|
||||
|
||||
<properties>
|
||||
<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;
|
||||
}
|
||||
}
|
|
@ -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)
|
|
@ -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)
|
||||
|
|
|
@ -5,4 +5,5 @@ This module contains articles about core features in the Java language
|
|||
### Relevant Articles:
|
||||
- [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)
|
||||
- [What is a POJO Class?](https://www.baeldung.com/java-pojo-class)
|
||||
- [[<-- Prev]](/core-java-modules/core-java-lang)
|
||||
|
|
|
@ -6,3 +6,4 @@
|
|||
- [Java 8 Math New Methods](https://www.baeldung.com/java-8-math)
|
||||
- [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)
|
||||
- [The strictfp Keyword in Java](https://www.baeldung.com/java-strictfp)
|
||||
|
|
|
@ -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();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -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)
|
||||
- [Guide to Java 8’s Collectors](https://www.baeldung.com/java-8-collectors)
|
||||
- [Primitive Type Streams in Java 8](https://www.baeldung.com/java-8-primitive-streams)
|
||||
- [Debugging Java 8 Streams with IntelliJ](https://www.baeldung.com/intellij-debugging-java-streams)
|
||||
- More articles: [[<-- prev>]](/../core-java-streams-2)
|
|
@ -58,7 +58,7 @@
|
|||
</build>
|
||||
|
||||
<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>
|
||||
<commons-codec.version>1.10</commons-codec.version>
|
||||
</properties>
|
||||
|
|
|
@ -1,6 +1,9 @@
|
|||
package com.baeldung.isnumeric;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Function;
|
||||
|
||||
import org.openjdk.jmh.annotations.Benchmark;
|
||||
import org.openjdk.jmh.annotations.BenchmarkMode;
|
||||
|
@ -14,6 +17,8 @@ import org.openjdk.jmh.runner.options.Options;
|
|||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
|
||||
public class Benchmarking {
|
||||
private static final TestMode MODE = TestMode.DIVERS;
|
||||
|
||||
public static void main(String[] args) throws RunnerException {
|
||||
Options opt = new OptionsBuilder().include(Benchmarking.class.getSimpleName())
|
||||
.forks(1)
|
||||
|
@ -22,52 +27,89 @@ public class Benchmarking {
|
|||
new Runner(opt).run();
|
||||
}
|
||||
|
||||
private static final IsNumeric subject = new IsNumeric();
|
||||
|
||||
@State(Scope.Thread)
|
||||
public static class ExecutionPlan {
|
||||
public String number = Integer.toString(Integer.MAX_VALUE);
|
||||
public boolean isNumber = false;
|
||||
public IsNumeric isNumeric = new IsNumeric();
|
||||
private final Map<String, Boolean> testPlan = testPlan();
|
||||
|
||||
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
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void usingCoreJava(ExecutionPlan plan) {
|
||||
plan.isNumber = plan.isNumeric.usingCoreJava(plan.number);
|
||||
plan.validate(subject::usingCoreJava);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void usingRegularExpressions(ExecutionPlan plan) {
|
||||
plan.isNumber = plan.isNumeric.usingRegularExpressions(plan.number);
|
||||
plan.validate(subject::usingPreCompiledRegularExpressions);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void usingNumberUtils_isCreatable(ExecutionPlan plan) {
|
||||
plan.isNumber = plan.isNumeric.usingNumberUtils_isCreatable(plan.number);
|
||||
plan.validate(subject::usingNumberUtils_isCreatable);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void usingNumberUtils_isParsable(ExecutionPlan plan) {
|
||||
plan.isNumber = plan.isNumeric.usingNumberUtils_isParsable(plan.number);
|
||||
plan.validate(subject::usingNumberUtils_isParsable);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void usingStringUtils_isNumeric(ExecutionPlan plan) {
|
||||
plan.isNumber = plan.isNumeric.usingStringUtils_isNumeric(plan.number);
|
||||
plan.validate(subject::usingStringUtils_isNumeric);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void usingStringUtils_isNumericSpace(ExecutionPlan plan) {
|
||||
plan.isNumber = plan.isNumeric.usingStringUtils_isNumericSpace(plan.number);
|
||||
plan.validate(subject::usingStringUtils_isNumericSpace);
|
||||
}
|
||||
|
||||
private enum TestMode {
|
||||
SIMPLE, DIVERS
|
||||
}
|
||||
}
|
|
@ -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");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,20 +1,33 @@
|
|||
package com.baeldung.isnumeric;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.math.NumberUtils;
|
||||
|
||||
public class IsNumeric {
|
||||
private final Pattern pattern = Pattern.compile("-?\\d+(\\.\\d+)?");
|
||||
|
||||
public boolean usingCoreJava(String strNum) {
|
||||
if (strNum == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
Double.parseDouble(strNum);
|
||||
} catch (NumberFormatException | NullPointerException nfe) {
|
||||
} catch (NumberFormatException nfe) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean usingRegularExpressions(String strNum) {
|
||||
return strNum.matches("-?\\d+(\\.\\d+)?");
|
||||
public boolean usingPreCompiledRegularExpressions(String strNum) {
|
||||
if (strNum == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return pattern.matcher(strNum)
|
||||
.matches();
|
||||
}
|
||||
|
||||
public boolean usingNumberUtils_isCreatable(String strNum) {
|
||||
|
|
|
@ -13,8 +13,8 @@ public class IsNumericDriver {
|
|||
boolean res = isNumeric.usingCoreJava("1001");
|
||||
LOG.info("Using Core Java : " + res);
|
||||
|
||||
res = isNumeric.usingRegularExpressions("1001");
|
||||
LOG.info("Using Regular Expressions : " + res);
|
||||
res = isNumeric.usingPreCompiledRegularExpressions("1001");
|
||||
LOG.info("Using Pre-compiled Regular Expressions : " + res);
|
||||
|
||||
res = isNumeric.usingNumberUtils_isCreatable("1001");
|
||||
LOG.info("Using NumberUtils.isCreatable : " + res);
|
||||
|
|
|
@ -6,9 +6,13 @@ import org.junit.Test;
|
|||
|
||||
public class CoreJavaIsNumericUnitTest {
|
||||
public static boolean isNumeric(String strNum) {
|
||||
if (strNum == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
double d = Double.parseDouble(strNum);
|
||||
} catch (NumberFormatException | NullPointerException nfe) {
|
||||
Double.parseDouble(strNum);
|
||||
} catch (NumberFormatException nfe) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
|
|
|
@ -2,11 +2,19 @@ package com.baeldung.isnumeric;
|
|||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class RegularExpressionsUnitTest {
|
||||
public static boolean isNumeric(String strNum) {
|
||||
return strNum.matches("-?\\d+(\\.\\d+)?");
|
||||
private final Pattern pattern = Pattern.compile("-?\\d+(\\.\\d+)?");
|
||||
|
||||
public boolean isNumeric(String strNum) {
|
||||
if (strNum == null) {
|
||||
return false;
|
||||
}
|
||||
return pattern.matcher(strNum)
|
||||
.matches();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -17,6 +25,7 @@ public class RegularExpressionsUnitTest {
|
|||
assertThat(isNumeric("-200")).isTrue();
|
||||
|
||||
// Invalid Numbers
|
||||
assertThat(isNumeric(null)).isFalse();
|
||||
assertThat(isNumeric("abc")).isFalse();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
- [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)
|
||||
|
|
|
@ -14,14 +14,6 @@
|
|||
|
||||
<dependencies>
|
||||
|
||||
<!-- marshalling -->
|
||||
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- YAML -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.dataformat</groupId>
|
||||
|
|
|
@ -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)
|
|
@ -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>
|
|
@ -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.ObjectIdGenerators;
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.jackson.bidirection;
|
||||
package com.baeldung.jackson.annotation.bidirection;
|
||||
|
||||
public class ItemWithIgnore {
|
||||
public int id;
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.jackson.bidirection;
|
||||
package com.baeldung.jackson.annotation.bidirection;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonManagedReference;
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.jackson.bidirection;
|
||||
package com.baeldung.jackson.annotation.bidirection;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.jackson.bidirection;
|
||||
package com.baeldung.jackson.annotation.bidirection;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.jackson.bidirection;
|
||||
package com.baeldung.jackson.annotation.bidirection;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.jackson.date;
|
||||
package com.baeldung.jackson.annotation.date;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.text.ParseException;
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.jackson.date;
|
||||
package com.baeldung.jackson.annotation.date;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.text.SimpleDateFormat;
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.jackson.date;
|
||||
package com.baeldung.jackson.annotation.date;
|
||||
|
||||
import java.util.Date;
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.jackson.date;
|
||||
package com.baeldung.jackson.annotation.date;
|
||||
|
||||
import java.util.Date;
|
||||
|
|
@ -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));
|
||||
}
|
||||
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.jackson.exception;
|
||||
package com.baeldung.jackson.annotation.exception;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonRootName;
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.jackson.exception;
|
||||
package com.baeldung.jackson.annotation.exception;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonRootName;
|
||||
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
package com.baeldung.jackson.annotation.jsonview;
|
||||
|
||||
public class Views {
|
||||
public static class Public {
|
||||
}
|
||||
|
||||
public static class Internal extends Public {
|
||||
}
|
||||
}
|
|
@ -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();
|
||||
}
|
||||
|
||||
}
|
|
@ -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
Loading…
Reference in New Issue