Merge branch 'master' of https://github.com/eugenp/tutorials
This commit is contained in:
commit
7f460e45f0
@ -11,4 +11,5 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
|
|||||||
- [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)
|
- [How to Determine if a Binary Tree is Balanced](https://www.baeldung.com/java-balanced-binary-tree)
|
||||||
- [The Caesar Cipher in Java](https://www.baeldung.com/java-caesar-cipher)
|
- [The Caesar Cipher in Java](https://www.baeldung.com/java-caesar-cipher)
|
||||||
|
- [Overview of Combinatorial Problems in Java](https://www.baeldung.com/java-combinatorial-algorithms)
|
||||||
- More articles: [[<-- prev]](/../algorithms-miscellaneous-4)
|
- More articles: [[<-- prev]](/../algorithms-miscellaneous-4)
|
||||||
|
@ -34,6 +34,11 @@
|
|||||||
<artifactId>tradukisto</artifactId>
|
<artifactId>tradukisto</artifactId>
|
||||||
<version>${tradukisto.version}</version>
|
<version>${tradukisto.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.google.guava</groupId>
|
||||||
|
<artifactId>guava</artifactId>
|
||||||
|
<version>28.1-jre</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.assertj</groupId>
|
<groupId>org.assertj</groupId>
|
||||||
|
@ -0,0 +1,72 @@
|
|||||||
|
package com.baeldung.algorithms.kruskal;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class CycleDetector {
|
||||||
|
|
||||||
|
List<DisjointSetInfo> nodes;
|
||||||
|
|
||||||
|
public CycleDetector(int totalNodes) {
|
||||||
|
initDisjointSets(totalNodes);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean detectCycle(Integer u, Integer v) {
|
||||||
|
Integer rootU = pathCompressionFind(u);
|
||||||
|
Integer rootV = pathCompressionFind(v);
|
||||||
|
if (rootU.equals(rootV)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
unionByRank(rootU, rootV);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void initDisjointSets(int totalNodes) {
|
||||||
|
nodes = new ArrayList<>(totalNodes);
|
||||||
|
for (int i = 0; i < totalNodes; i++) {
|
||||||
|
nodes.add(new DisjointSetInfo(i));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Integer find(Integer node) {
|
||||||
|
Integer parent = nodes.get(node).getParentNode();
|
||||||
|
if (parent.equals(node)) {
|
||||||
|
return node;
|
||||||
|
} else {
|
||||||
|
return find(parent);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Integer pathCompressionFind(Integer node) {
|
||||||
|
DisjointSetInfo setInfo = nodes.get(node);
|
||||||
|
Integer parent = setInfo.getParentNode();
|
||||||
|
if (parent.equals(node)) {
|
||||||
|
return node;
|
||||||
|
} else {
|
||||||
|
Integer parentNode = find(parent);
|
||||||
|
setInfo.setParentNode(parentNode);
|
||||||
|
return parentNode;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void union(Integer rootU, Integer rootV) {
|
||||||
|
DisjointSetInfo setInfoU = nodes.get(rootU);
|
||||||
|
setInfoU.setParentNode(rootV);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void unionByRank(int rootU, int rootV) {
|
||||||
|
DisjointSetInfo setInfoU = nodes.get(rootU);
|
||||||
|
DisjointSetInfo setInfoV = nodes.get(rootV);
|
||||||
|
int rankU = setInfoU.getRank();
|
||||||
|
int rankV = setInfoV.getRank();
|
||||||
|
if (rankU < rankV) {
|
||||||
|
setInfoU.setParentNode(rootV);
|
||||||
|
} else {
|
||||||
|
setInfoV.setParentNode(rootU);
|
||||||
|
if (rankU == rankV) {
|
||||||
|
setInfoU.setRank(rankU + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,28 @@
|
|||||||
|
package com.baeldung.algorithms.kruskal;
|
||||||
|
|
||||||
|
public class DisjointSetInfo {
|
||||||
|
|
||||||
|
private Integer parentNode;
|
||||||
|
private int rank;
|
||||||
|
|
||||||
|
DisjointSetInfo(Integer nodeNumber) {
|
||||||
|
setParentNode(nodeNumber);
|
||||||
|
setRank(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Integer getParentNode() {
|
||||||
|
return parentNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setParentNode(Integer parentNode) {
|
||||||
|
this.parentNode = parentNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getRank() {
|
||||||
|
return rank;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setRank(int rank) {
|
||||||
|
this.rank = rank;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,53 @@
|
|||||||
|
package com.baeldung.algorithms.kruskal;
|
||||||
|
|
||||||
|
import com.google.common.graph.EndpointPair;
|
||||||
|
import com.google.common.graph.MutableValueGraph;
|
||||||
|
import com.google.common.graph.ValueGraph;
|
||||||
|
import com.google.common.graph.ValueGraphBuilder;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
public class Kruskal {
|
||||||
|
|
||||||
|
public ValueGraph<Integer, Double> minSpanningTree(ValueGraph<Integer, Double> graph) {
|
||||||
|
|
||||||
|
return spanningTree(graph, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
public ValueGraph<Integer, Double> maxSpanningTree(ValueGraph<Integer, Double> graph) {
|
||||||
|
return spanningTree(graph, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private ValueGraph<Integer, Double> spanningTree(ValueGraph<Integer, Double> graph, boolean minSpanningTree) {
|
||||||
|
Set<EndpointPair<Integer>> edges = graph.edges();
|
||||||
|
List<EndpointPair<Integer>> edgeList = new ArrayList<>(edges);
|
||||||
|
|
||||||
|
if (minSpanningTree) {
|
||||||
|
edgeList.sort(Comparator.comparing(e -> graph.edgeValue(e).get()));
|
||||||
|
} else {
|
||||||
|
edgeList.sort(Collections.reverseOrder(Comparator.comparing(e -> graph.edgeValue(e).get())));
|
||||||
|
}
|
||||||
|
|
||||||
|
int totalNodes = graph.nodes().size();
|
||||||
|
CycleDetector cycleDetector = new CycleDetector(totalNodes);
|
||||||
|
int edgeCount = 0;
|
||||||
|
|
||||||
|
MutableValueGraph<Integer, Double> spanningTree = ValueGraphBuilder.undirected().build();
|
||||||
|
for (EndpointPair<Integer> edge : edgeList) {
|
||||||
|
if (cycleDetector.detectCycle(edge.nodeU(), edge.nodeV())) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
spanningTree.putEdgeValue(edge.nodeU(), edge.nodeV(), graph.edgeValue(edge).get());
|
||||||
|
edgeCount++;
|
||||||
|
if (edgeCount == totalNodes - 1) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return spanningTree;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,67 @@
|
|||||||
|
package com.baeldung.algorithms.kruskal;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
import com.google.common.graph.MutableValueGraph;
|
||||||
|
import com.google.common.graph.ValueGraph;
|
||||||
|
import com.google.common.graph.ValueGraphBuilder;
|
||||||
|
import com.baeldung.algorithms.kruskal.Kruskal;
|
||||||
|
|
||||||
|
public class KruskalUnitTest {
|
||||||
|
|
||||||
|
private MutableValueGraph<Integer, Double> graph;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setup() {
|
||||||
|
graph = ValueGraphBuilder.undirected().build();
|
||||||
|
graph.putEdgeValue(0, 1, 8.0);
|
||||||
|
graph.putEdgeValue(0, 2, 5.0);
|
||||||
|
graph.putEdgeValue(1, 2, 9.0);
|
||||||
|
graph.putEdgeValue(1, 3, 11.0);
|
||||||
|
graph.putEdgeValue(2, 3, 15.0);
|
||||||
|
graph.putEdgeValue(2, 4, 10.0);
|
||||||
|
graph.putEdgeValue(3, 4, 7.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenGraph_whenMinimumSpanningTree_thenOutputCorrectResult() {
|
||||||
|
final Kruskal kruskal = new Kruskal();
|
||||||
|
ValueGraph<Integer, Double> spanningTree = kruskal.minSpanningTree(graph);
|
||||||
|
|
||||||
|
assertTrue(spanningTree.hasEdgeConnecting(0, 1));
|
||||||
|
assertTrue(spanningTree.hasEdgeConnecting(0, 2));
|
||||||
|
assertTrue(spanningTree.hasEdgeConnecting(2, 4));
|
||||||
|
assertTrue(spanningTree.hasEdgeConnecting(3, 4));
|
||||||
|
assertEquals(graph.edgeValue(0, 1), spanningTree.edgeValue(0, 1));
|
||||||
|
assertEquals(graph.edgeValue(0, 2), spanningTree.edgeValue(0, 2));
|
||||||
|
assertEquals(graph.edgeValue(2, 4), spanningTree.edgeValue(2, 4));
|
||||||
|
assertEquals(graph.edgeValue(3, 4), spanningTree.edgeValue(3, 4));
|
||||||
|
|
||||||
|
assertFalse(spanningTree.hasEdgeConnecting(1, 2));
|
||||||
|
assertFalse(spanningTree.hasEdgeConnecting(1, 3));
|
||||||
|
assertFalse(spanningTree.hasEdgeConnecting(2, 3));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenGraph_whenMaximumSpanningTree_thenOutputCorrectResult() {
|
||||||
|
final Kruskal kruskal = new Kruskal();
|
||||||
|
ValueGraph<Integer, Double> spanningTree = kruskal.maxSpanningTree(graph);
|
||||||
|
|
||||||
|
assertTrue(spanningTree.hasEdgeConnecting(0, 1));
|
||||||
|
assertTrue(spanningTree.hasEdgeConnecting(1, 3));
|
||||||
|
assertTrue(spanningTree.hasEdgeConnecting(2, 3));
|
||||||
|
assertTrue(spanningTree.hasEdgeConnecting(2, 4));
|
||||||
|
assertEquals(graph.edgeValue(0, 1), spanningTree.edgeValue(0, 1));
|
||||||
|
assertEquals(graph.edgeValue(1, 3), spanningTree.edgeValue(1, 3));
|
||||||
|
assertEquals(graph.edgeValue(2, 3), spanningTree.edgeValue(2, 3));
|
||||||
|
assertEquals(graph.edgeValue(2, 4), spanningTree.edgeValue(2, 4));
|
||||||
|
|
||||||
|
assertFalse(spanningTree.hasEdgeConnecting(0, 2));
|
||||||
|
assertFalse(spanningTree.hasEdgeConnecting(1, 2));
|
||||||
|
assertFalse(spanningTree.hasEdgeConnecting(3, 4));
|
||||||
|
}
|
||||||
|
}
|
@ -14,7 +14,7 @@ import static org.junit.Assert.assertTrue;
|
|||||||
public class PatternJava11UnitTest {
|
public class PatternJava11UnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenPreCompiledPattern_whenCallAsMatchPredicate_thenReturnMatchPredicateToMatchesThePatternInTheListElements() {
|
public void givenPreCompiledPattern_whenCallAsMatchPredicate_thenReturnMatchPredicateToMatchesPattern() {
|
||||||
List<String> namesToValidate = Arrays.asList("Fabio Silva", "Fabio Luis Silva");
|
List<String> namesToValidate = Arrays.asList("Fabio Silva", "Fabio Luis Silva");
|
||||||
Pattern firstLastNamePreCompiledPattern = Pattern.compile("[a-zA-Z]{3,} [a-zA-Z]{3,}");
|
Pattern firstLastNamePreCompiledPattern = Pattern.compile("[a-zA-Z]{3,} [a-zA-Z]{3,}");
|
||||||
|
|
||||||
|
@ -1,9 +1,8 @@
|
|||||||
package com.baeldung.timezone;
|
package com.baeldung.jvmtimezone;
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import java.util.Calendar;
|
import java.util.Calendar;
|
||||||
import java.util.Date;
|
|
||||||
import java.util.TimeZone;
|
import java.util.TimeZone;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
@ -13,9 +12,7 @@ public class ModifyDefaultTimezoneUnitTest {
|
|||||||
@Test
|
@Test
|
||||||
public void givenDefaultTimezoneSet_thenDateTimezoneIsCorrect() {
|
public void givenDefaultTimezoneSet_thenDateTimezoneIsCorrect() {
|
||||||
TimeZone.setDefault(TimeZone.getTimeZone("Portugal"));
|
TimeZone.setDefault(TimeZone.getTimeZone("Portugal"));
|
||||||
Date date = new Date();
|
|
||||||
Calendar calendar = Calendar.getInstance();
|
Calendar calendar = Calendar.getInstance();
|
||||||
calendar.setTime(date);
|
|
||||||
assertEquals(calendar.getTimeZone(), TimeZone.getTimeZone("Portugal"));
|
assertEquals(calendar.getTimeZone(), TimeZone.getTimeZone("Portugal"));
|
||||||
}
|
}
|
||||||
|
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.timezone;
|
package com.baeldung.jvmtimezone;
|
||||||
|
|
||||||
import org.junit.After;
|
import org.junit.After;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
@ -14,7 +14,7 @@ public class ModifyTimezonePropertyUnitTest {
|
|||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void setup() {
|
public void setup() {
|
||||||
System.setProperty("user.timezone", "IST");
|
System.setProperty("user.timezone", "Asia/Kolkata");
|
||||||
TimeZone.setDefault(null);
|
TimeZone.setDefault(null);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -25,10 +25,8 @@ public class ModifyTimezonePropertyUnitTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenTimezonePropertySet_thenDateTimezoneIsCorrect() {
|
public void givenTimezonePropertySet_thenDateTimezoneIsCorrect() {
|
||||||
Date date = new Date();
|
|
||||||
Calendar calendar = Calendar.getInstance();
|
Calendar calendar = Calendar.getInstance();
|
||||||
calendar.setTime(date);
|
assertEquals(calendar.getTimeZone(), TimeZone.getTimeZone("Asia/Kolkata"));
|
||||||
assertEquals(calendar.getTimeZone(), TimeZone.getTimeZone("IST"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
@ -0,0 +1,38 @@
|
|||||||
|
package com.baeldung.exceptions;
|
||||||
|
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
public class CatchingThrowable {
|
||||||
|
|
||||||
|
class CapacityException extends Exception {
|
||||||
|
CapacityException(String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class StorageAPI {
|
||||||
|
|
||||||
|
public void addIDsToStorage(int capacity, Set<String> storage) throws CapacityException {
|
||||||
|
if (capacity < 1) {
|
||||||
|
throw new CapacityException("Capacity of less than 1 is not allowed");
|
||||||
|
}
|
||||||
|
int count = 0;
|
||||||
|
while (count < capacity) {
|
||||||
|
storage.add(UUID.randomUUID().toString());
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// other methods go here ...
|
||||||
|
}
|
||||||
|
|
||||||
|
public void add(StorageAPI api, int capacity, Set<String> storage) {
|
||||||
|
try {
|
||||||
|
api.addIDsToStorage(capacity, storage);
|
||||||
|
} catch (Throwable throwable) {
|
||||||
|
// do something here
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -11,4 +11,5 @@ This module contains articles about Java operators
|
|||||||
- [Java Compound Operators](https://www.baeldung.com/java-compound-operators)
|
- [Java Compound Operators](https://www.baeldung.com/java-compound-operators)
|
||||||
- [The XOR Operator in Java](https://www.baeldung.com/java-xor-operator)
|
- [The XOR Operator in Java](https://www.baeldung.com/java-xor-operator)
|
||||||
- [Java Bitwise Operators](https://www.baeldung.com/java-bitwise-operators)
|
- [Java Bitwise Operators](https://www.baeldung.com/java-bitwise-operators)
|
||||||
|
- [Bitwise & vs Logical && Operators](https://www.baeldung.com/bitwise-vs-logical-operators/)
|
||||||
|
|
||||||
|
@ -0,0 +1,71 @@
|
|||||||
|
package com.baeldung.andoperators;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
|
public class BitwiseAndLogicalANDOperatorsUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoTrueBooleans_whenBitwiseAndOperator_thenTrue() {
|
||||||
|
boolean trueBool = true;
|
||||||
|
boolean anotherTrueBool = true;
|
||||||
|
boolean trueANDTrue = trueBool & anotherTrueBool;
|
||||||
|
assertTrue(trueANDTrue);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenOneFalseAndOneTrueBooleans_whenBitwiseAndOperator_thenFalse() {
|
||||||
|
boolean trueBool = true;
|
||||||
|
boolean falseBool = false;
|
||||||
|
boolean trueANDFalse = trueBool & falseBool;
|
||||||
|
assertFalse(trueANDFalse);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoFalseBooleans_whenBitwiseAndOperator_thenFalse() {
|
||||||
|
boolean falseBool = false;
|
||||||
|
boolean anotherFalseBool = false;
|
||||||
|
boolean falseANDFalse = falseBool & anotherFalseBool;
|
||||||
|
assertFalse(falseANDFalse);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoIntegers_whenBitwiseAndOperator_thenNewDecimalNumber() {
|
||||||
|
int six = 6;
|
||||||
|
int five = 5;
|
||||||
|
int shouldBeFour = six & five;
|
||||||
|
assertEquals(4, shouldBeFour);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoTrueBooleans_whenLogicalAndOperator_thenTrue() {
|
||||||
|
boolean trueBool = true;
|
||||||
|
boolean anotherTrueBool = true;
|
||||||
|
boolean trueANDTrue = trueBool && anotherTrueBool;
|
||||||
|
assertTrue(trueANDTrue);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenOneFalseAndOneTrueBooleans_whenLogicalAndOperator_thenFalse() {
|
||||||
|
boolean trueBool = true;
|
||||||
|
boolean falseBool = false;
|
||||||
|
boolean trueANDFalse = trueBool && falseBool;
|
||||||
|
assertFalse(trueANDFalse);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoFalseBooleans_whenLogicalAndOperator_thenFalse() {
|
||||||
|
boolean falseBool = false;
|
||||||
|
boolean anotherFalseBool = false;
|
||||||
|
boolean falseANDFalse = falseBool && anotherFalseBool;
|
||||||
|
assertFalse(falseANDFalse);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoFalseExpressions_whenLogicalAndOperator_thenShortCircuitFalse() {
|
||||||
|
boolean shortCircuitResult = (2<1) && (4<5);
|
||||||
|
assertFalse(shortCircuitResult);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,99 @@
|
|||||||
|
package com.baeldung.core.operators.notoperator;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Examples used in the article `Using the Not Operator in If Conditions in Java`.
|
||||||
|
*/
|
||||||
|
public class NotOperator {
|
||||||
|
|
||||||
|
public static void ifElseStatementExample() {
|
||||||
|
boolean isValid = true;
|
||||||
|
|
||||||
|
if (isValid) {
|
||||||
|
System.out.println("Valid");
|
||||||
|
} else {
|
||||||
|
System.out.println("Invalid");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void checkIsValidIsFalseWithEmptyIfBlock() {
|
||||||
|
boolean isValid = true;
|
||||||
|
|
||||||
|
if (isValid) {
|
||||||
|
|
||||||
|
} else {
|
||||||
|
System.out.println("Invalid");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void checkIsValidIsFalseWithJustTheIfBlock() {
|
||||||
|
boolean isValid = true;
|
||||||
|
|
||||||
|
if (isValid == false) {
|
||||||
|
System.out.println("Invalid");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void checkIsValidIsFalseWithTheNotOperator() {
|
||||||
|
boolean isValid = true;
|
||||||
|
|
||||||
|
if (!isValid) {
|
||||||
|
System.out.println("Invalid");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void notOperatorWithBooleanValueAsOperand() {
|
||||||
|
System.out.println(!true); // prints false
|
||||||
|
System.out.println(!false); // prints true
|
||||||
|
System.out.println(!!false); // prints false
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void applyNotOperatorToAnExpression_example1() {
|
||||||
|
int count = 2;
|
||||||
|
|
||||||
|
System.out.println(!(count > 2)); // prints true
|
||||||
|
System.out.println(!(count <= 2)); // prints false
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void applyNotOperatorToAnExpression_LogicalOperators() {
|
||||||
|
boolean x = true;
|
||||||
|
boolean y = false;
|
||||||
|
|
||||||
|
System.out.println(!(x && y)); // prints true
|
||||||
|
System.out.println(!(x || y)); // prints false
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void precedence_example() {
|
||||||
|
boolean x = true;
|
||||||
|
boolean y = false;
|
||||||
|
|
||||||
|
System.out.println(!x && y); // prints false
|
||||||
|
System.out.println(!(x && y)); // prints true
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void pitfalls_ComplexConditionsExample() {
|
||||||
|
int count = 9;
|
||||||
|
int total = 100;
|
||||||
|
|
||||||
|
if (!(count >= 10 || total >= 1000)) {
|
||||||
|
System.out.println("Some more work to do");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void pitfalls_simplifyComplexConditionsByReversingLogicExample() {
|
||||||
|
int count = 9;
|
||||||
|
int total = 100;
|
||||||
|
|
||||||
|
if (count < 10 && total < 1000) {
|
||||||
|
System.out.println("Some more work to do");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void exitEarlyExample() {
|
||||||
|
boolean isValid = false;
|
||||||
|
|
||||||
|
if(!isValid) {
|
||||||
|
throw new IllegalArgumentException("Invalid input");
|
||||||
|
}
|
||||||
|
// Code to execute when isValid == true goes here
|
||||||
|
}
|
||||||
|
}
|
@ -1,72 +1,103 @@
|
|||||||
package com.baeldung.randomstrings;
|
package com.baeldung.randomstrings;
|
||||||
|
|
||||||
import org.apache.commons.lang3.RandomStringUtils;
|
import org.apache.commons.lang3.RandomStringUtils;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import java.nio.charset.Charset;
|
import java.nio.charset.Charset;
|
||||||
import java.util.Random;
|
import java.util.Random;
|
||||||
|
|
||||||
public class RandomStringsUnitTest {
|
public class RandomStringsUnitTest {
|
||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(RandomStringsUnitTest.class);
|
private static final Logger LOG = LoggerFactory.getLogger(RandomStringsUnitTest.class);
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenUsingPlainJava_whenGeneratingRandomStringUnbounded_thenCorrect() {
|
public void givenUsingPlainJava_whenGeneratingRandomStringUnbounded_thenCorrect() {
|
||||||
final byte[] array = new byte[7]; // length is bounded by 7
|
byte[] array = new byte[7]; // length is bounded by 7
|
||||||
new Random().nextBytes(array);
|
new Random().nextBytes(array);
|
||||||
final String generatedString = new String(array, Charset.forName("UTF-8"));
|
String generatedString = new String(array, Charset.forName("UTF-8"));
|
||||||
|
|
||||||
LOG.debug(generatedString);
|
LOG.debug(generatedString);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenUsingPlainJava_whenGeneratingRandomStringBounded_thenCorrect() {
|
public void givenUsingPlainJava_whenGeneratingRandomStringBounded_thenCorrect() {
|
||||||
final int leftLimit = 97; // letter 'a'
|
int leftLimit = 97; // letter 'a'
|
||||||
final int rightLimit = 122; // letter 'z'
|
int rightLimit = 122; // letter 'z'
|
||||||
final int targetStringLength = 10;
|
int targetStringLength = 10;
|
||||||
final Random random = new Random();
|
Random random = new Random();
|
||||||
final StringBuilder buffer = new StringBuilder(targetStringLength);
|
StringBuilder buffer = new StringBuilder(targetStringLength);
|
||||||
|
|
||||||
for (int i = 0; i < targetStringLength; i++) {
|
for (int i = 0; i < targetStringLength; i++) {
|
||||||
final int randomLimitedInt = leftLimit + (int) (random.nextFloat() * (rightLimit - leftLimit + 1));
|
int randomLimitedInt = leftLimit + (int) (random.nextFloat() * (rightLimit - leftLimit + 1));
|
||||||
buffer.append((char) randomLimitedInt);
|
buffer.append((char) randomLimitedInt);
|
||||||
}
|
}
|
||||||
final String generatedString = buffer.toString();
|
String generatedString = buffer.toString();
|
||||||
|
|
||||||
LOG.debug(generatedString);
|
LOG.debug(generatedString);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenUsingApache_whenGeneratingRandomString_thenCorrect() {
|
public void givenUsingJava8_whenGeneratingRandomAlphabeticString_thenCorrect() {
|
||||||
final String generatedString = RandomStringUtils.random(10);
|
int leftLimit = 97; // letter 'a'
|
||||||
|
int rightLimit = 122; // letter 'z'
|
||||||
LOG.debug(generatedString);
|
int targetStringLength = 10;
|
||||||
}
|
Random random = new Random();
|
||||||
|
|
||||||
@Test
|
String generatedString = random.ints(leftLimit, rightLimit + 1)
|
||||||
public void givenUsingApache_whenGeneratingRandomAlphabeticString_thenCorrect() {
|
.limit(targetStringLength)
|
||||||
final String generatedString = RandomStringUtils.randomAlphabetic(10);
|
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
|
||||||
|
.toString();
|
||||||
LOG.debug(generatedString);
|
|
||||||
}
|
LOG.debug(generatedString);
|
||||||
|
}
|
||||||
@Test
|
|
||||||
public void givenUsingApache_whenGeneratingRandomAlphanumericString_thenCorrect() {
|
@Test
|
||||||
final String generatedString = RandomStringUtils.randomAlphanumeric(10);
|
public void givenUsingJava8_whenGeneratingRandomAlphanumericString_thenCorrect() {
|
||||||
|
int leftLimit = 48; // numeral '0'
|
||||||
LOG.debug(generatedString);
|
int rightLimit = 122; // letter 'z'
|
||||||
}
|
int targetStringLength = 10;
|
||||||
|
Random random = new Random();
|
||||||
@Test
|
|
||||||
public void givenUsingApache_whenGeneratingRandomStringBounded_thenCorrect() {
|
String generatedString = random.ints(leftLimit, rightLimit + 1)
|
||||||
final int length = 10;
|
.filter(i -> (i <= 57 || i >= 65) && (i <= 90 || i >= 97))
|
||||||
final boolean useLetters = true;
|
.limit(targetStringLength)
|
||||||
final boolean useNumbers = false;
|
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
|
||||||
final String generatedString = RandomStringUtils.random(length, useLetters, useNumbers);
|
.toString();
|
||||||
|
|
||||||
LOG.debug(generatedString);
|
LOG.debug(generatedString);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
@Test
|
||||||
|
public void givenUsingApache_whenGeneratingRandomString_thenCorrect() {
|
||||||
|
String generatedString = RandomStringUtils.random(10);
|
||||||
|
|
||||||
|
LOG.debug(generatedString);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUsingApache_whenGeneratingRandomAlphabeticString_thenCorrect() {
|
||||||
|
String generatedString = RandomStringUtils.randomAlphabetic(10);
|
||||||
|
|
||||||
|
LOG.debug(generatedString);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUsingApache_whenGeneratingRandomAlphanumericString_thenCorrect() {
|
||||||
|
String generatedString = RandomStringUtils.randomAlphanumeric(10);
|
||||||
|
|
||||||
|
LOG.debug(generatedString);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUsingApache_whenGeneratingRandomStringBounded_thenCorrect() {
|
||||||
|
int length = 10;
|
||||||
|
boolean useLetters = true;
|
||||||
|
boolean useNumbers = false;
|
||||||
|
String generatedString = RandomStringUtils.random(length, useLetters, useNumbers);
|
||||||
|
|
||||||
|
LOG.debug(generatedString);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
@ -30,7 +30,7 @@ public class PatternUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenPreCompiledPattern_whenCallAsPredicate_thenReturnPredicateToFindThePatternInTheListElements() {
|
public void givenPreCompiledPattern_whenCallAsPredicate_thenReturnPredicateToFindPatternInTheList() {
|
||||||
List<String> namesToValidate = Arrays.asList("Fabio Silva", "Mr. Silva");
|
List<String> namesToValidate = Arrays.asList("Fabio Silva", "Mr. Silva");
|
||||||
Predicate<String> patternsAsPredicate = FIRST_LAST_NAME_PRE_COMPILED_PATTERN.asPredicate();
|
Predicate<String> patternsAsPredicate = FIRST_LAST_NAME_PRE_COMPILED_PATTERN.asPredicate();
|
||||||
|
|
||||||
@ -52,7 +52,7 @@ public class PatternUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenPreCompiledPattern_whenCallSplitAsStream_thenReturnArrayWithValuesSplitByThePattern() {
|
public void givenPreCompiledPattern_whenCallSplitAsStream_thenReturnArraySplitByThePattern() {
|
||||||
Stream<String> textSplitAsStream = SPLIT_PRE_COMPILED_PATTERN.splitAsStream("My_Name__is__Fabio_Silva");
|
Stream<String> textSplitAsStream = SPLIT_PRE_COMPILED_PATTERN.splitAsStream("My_Name__is__Fabio_Silva");
|
||||||
String[] textSplit = textSplitAsStream.toArray(String[]::new);
|
String[] textSplit = textSplitAsStream.toArray(String[]::new);
|
||||||
|
|
||||||
|
@ -8,22 +8,11 @@
|
|||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>parent-java</artifactId>
|
<artifactId>jackson-modules</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
<relativePath>../parent-java</relativePath>
|
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<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>
|
<dependency>
|
||||||
<groupId>com.fasterxml.jackson.module</groupId>
|
<groupId>com.fasterxml.jackson.module</groupId>
|
||||||
<artifactId>jackson-module-jsonSchema</artifactId>
|
<artifactId>jackson-module-jsonSchema</artifactId>
|
@ -8,23 +8,11 @@
|
|||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>parent-java</artifactId>
|
<artifactId>jackson-modules</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
<relativePath>../parent-java</relativePath>
|
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
|
||||||
<groupId>com.fasterxml.jackson.core</groupId>
|
|
||||||
<artifactId>jackson-databind</artifactId>
|
|
||||||
<version>${jackson.version}</version>
|
|
||||||
</dependency>
|
|
||||||
<!--jackson for xml -->
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.fasterxml.jackson.dataformat</groupId>
|
|
||||||
<artifactId>jackson-dataformat-xml</artifactId>
|
|
||||||
<version>${jackson.version}</version>
|
|
||||||
</dependency>
|
|
||||||
<!-- YAML -->
|
<!-- YAML -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.fasterxml.jackson.dataformat</groupId>
|
<groupId>com.fasterxml.jackson.dataformat</groupId>
|
@ -8,17 +8,11 @@
|
|||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>parent-java</artifactId>
|
<artifactId>jackson-modules</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
<relativePath>../parent-java</relativePath>
|
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
|
||||||
<groupId>com.fasterxml.jackson.core</groupId>
|
|
||||||
<artifactId>jackson-databind</artifactId>
|
|
||||||
<version>${jackson.version}</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.fasterxml.jackson.datatype</groupId>
|
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||||
<artifactId>jackson-datatype-joda</artifactId>
|
<artifactId>jackson-datatype-joda</artifactId>
|
||||||
@ -29,12 +23,6 @@
|
|||||||
<artifactId>jackson-datatype-jsr310</artifactId>
|
<artifactId>jackson-datatype-jsr310</artifactId>
|
||||||
<version>${jackson.version}</version>
|
<version>${jackson.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<!--jackson for xml -->
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.fasterxml.jackson.dataformat</groupId>
|
|
||||||
<artifactId>jackson-dataformat-xml</artifactId>
|
|
||||||
<version>${jackson.version}</version>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user