Merge branch 'master' of https://github.com/chris9408/tutorials into feature/selenium-cookies
This commit is contained in:
commit
d137de913b
@ -10,4 +10,6 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
|
||||
- [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)
|
||||
- [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)
|
||||
|
@ -0,0 +1,42 @@
|
||||
package com.baeldung.algorithms.integerstreammedian;
|
||||
|
||||
import java.util.PriorityQueue;
|
||||
import java.util.Queue;
|
||||
|
||||
import static java.util.Comparator.reverseOrder;
|
||||
|
||||
public class MedianOfIntegerStream {
|
||||
|
||||
private Queue<Integer> minHeap, maxHeap;
|
||||
|
||||
MedianOfIntegerStream() {
|
||||
minHeap = new PriorityQueue<>();
|
||||
maxHeap = new PriorityQueue<>(reverseOrder());
|
||||
}
|
||||
|
||||
void add(int num) {
|
||||
if (!minHeap.isEmpty() && num < minHeap.peek()) {
|
||||
maxHeap.offer(num);
|
||||
if (maxHeap.size() > minHeap.size() + 1) {
|
||||
minHeap.offer(maxHeap.poll());
|
||||
}
|
||||
} else {
|
||||
minHeap.offer(num);
|
||||
if (minHeap.size() > maxHeap.size() + 1) {
|
||||
maxHeap.offer(minHeap.poll());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
double getMedian() {
|
||||
int median;
|
||||
if (minHeap.size() < maxHeap.size()) {
|
||||
median = maxHeap.peek();
|
||||
} else if (minHeap.size() > maxHeap.size()) {
|
||||
median = minHeap.peek();
|
||||
} else {
|
||||
median = (minHeap.peek() + maxHeap.peek()) / 2;
|
||||
}
|
||||
return median;
|
||||
}
|
||||
}
|
@ -0,0 +1,36 @@
|
||||
package com.baeldung.algorithms.integerstreammedian;
|
||||
|
||||
import java.util.PriorityQueue;
|
||||
import java.util.Queue;
|
||||
|
||||
import static java.util.Comparator.reverseOrder;
|
||||
|
||||
public class MedianOfIntegerStream2 {
|
||||
|
||||
private Queue<Integer> minHeap, maxHeap;
|
||||
|
||||
MedianOfIntegerStream2() {
|
||||
minHeap = new PriorityQueue<>();
|
||||
maxHeap = new PriorityQueue<>(reverseOrder());
|
||||
}
|
||||
|
||||
void add(int num) {
|
||||
if (minHeap.size() == maxHeap.size()) {
|
||||
maxHeap.offer(num);
|
||||
minHeap.offer(maxHeap.poll());
|
||||
} else {
|
||||
minHeap.offer(num);
|
||||
maxHeap.offer(minHeap.poll());
|
||||
}
|
||||
}
|
||||
|
||||
double getMedian() {
|
||||
int median;
|
||||
if (minHeap.size() > maxHeap.size()) {
|
||||
median = minHeap.peek();
|
||||
} else {
|
||||
median = (minHeap.peek() + maxHeap.peek()) / 2;
|
||||
}
|
||||
return median;
|
||||
}
|
||||
}
|
@ -0,0 +1,41 @@
|
||||
package com.baeldung.algorithms.integerstreammedian;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class MedianOfIntegerStreamUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenStreamOfIntegers_whenAnElementIsRead_thenMedianChangesWithApproach1() {
|
||||
MedianOfIntegerStream mis = new MedianOfIntegerStream();
|
||||
for (Map.Entry<Integer, Double> e : testcaseFixture().entrySet()) {
|
||||
mis.add(e.getKey());
|
||||
assertEquals(e.getValue(), (Double) mis.getMedian());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStreamOfIntegers_whenAnElementIsRead_thenMedianChangesWithApproach2() {
|
||||
MedianOfIntegerStream2 mis = new MedianOfIntegerStream2();
|
||||
for (Map.Entry<Integer, Double> e : testcaseFixture().entrySet()) {
|
||||
mis.add(e.getKey());
|
||||
assertEquals(e.getValue(), (Double) mis.getMedian());
|
||||
}
|
||||
}
|
||||
|
||||
private Map<Integer, Double> testcaseFixture() {
|
||||
return new LinkedHashMap<Integer, Double>() {{
|
||||
put(1, 1d);
|
||||
put(7, 4d);
|
||||
put(5, 5d);
|
||||
put(8, 6d);
|
||||
put(3, 5d);
|
||||
put(9, 6d);
|
||||
put(4, 5d);
|
||||
}};
|
||||
}
|
||||
}
|
@ -12,3 +12,4 @@ This module contains articles about Java 11 core features
|
||||
- [An Introduction to Epsilon GC: A No-Op Experimental Garbage Collector](https://www.baeldung.com/jvm-epsilon-gc-garbage-collector)
|
||||
- [Guide to jlink](https://www.baeldung.com/jlink)
|
||||
- [Negate a Predicate Method Reference with Java 11](https://www.baeldung.com/java-negate-predicate-method-reference)
|
||||
- [Benchmark JDK Collections vs Eclipse Collections](https://www.baeldung.com/jdk-collections-vs-eclipse-collections)
|
||||
|
@ -0,0 +1,29 @@
|
||||
package com.baeldung.patternreuse;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class PatternJava11UnitTest {
|
||||
|
||||
@Test
|
||||
public void givenPreCompiledPattern_whenCallAsMatchPredicate_thenReturnMatchPredicateToMatchesPattern() {
|
||||
List<String> namesToValidate = Arrays.asList("Fabio Silva", "Fabio Luis Silva");
|
||||
Pattern firstLastNamePreCompiledPattern = Pattern.compile("[a-zA-Z]{3,} [a-zA-Z]{3,}");
|
||||
|
||||
Predicate<String> patternAsMatchPredicate = firstLastNamePreCompiledPattern.asMatchPredicate();
|
||||
List<String> validatedNames = namesToValidate.stream()
|
||||
.filter(patternAsMatchPredicate)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertTrue(validatedNames.contains("Fabio Silva"));
|
||||
assertFalse(validatedNames.contains("Fabio Luis Silva"));
|
||||
}
|
||||
}
|
@ -1,9 +1,8 @@
|
||||
package com.baeldung.timezone;
|
||||
package com.baeldung.jvmtimezone;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
@ -13,9 +12,7 @@ public class ModifyDefaultTimezoneUnitTest {
|
||||
@Test
|
||||
public void givenDefaultTimezoneSet_thenDateTimezoneIsCorrect() {
|
||||
TimeZone.setDefault(TimeZone.getTimeZone("Portugal"));
|
||||
Date date = new Date();
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
assertEquals(calendar.getTimeZone(), TimeZone.getTimeZone("Portugal"));
|
||||
}
|
||||
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.timezone;
|
||||
package com.baeldung.jvmtimezone;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
@ -14,7 +14,7 @@ public class ModifyTimezonePropertyUnitTest {
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
System.setProperty("user.timezone", "IST");
|
||||
System.setProperty("user.timezone", "Asia/Kolkata");
|
||||
TimeZone.setDefault(null);
|
||||
}
|
||||
|
||||
@ -25,10 +25,8 @@ public class ModifyTimezonePropertyUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenTimezonePropertySet_thenDateTimezoneIsCorrect() {
|
||||
Date date = new Date();
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
assertEquals(calendar.getTimeZone(), TimeZone.getTimeZone("IST"));
|
||||
assertEquals(calendar.getTimeZone(), TimeZone.getTimeZone("Asia/Kolkata"));
|
||||
}
|
||||
|
||||
}
|
@ -7,3 +7,5 @@
|
||||
- [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)
|
||||
- [Basic Calculator in Java](https://www.baeldung.com/java-basic-calculator)
|
||||
- [Overflow and Underflow in Java](https://www.baeldung.com/java-overflow-underflow)
|
||||
|
@ -11,4 +11,5 @@ This module contains articles about Java operators
|
||||
- [Java Compound Operators](https://www.baeldung.com/java-compound-operators)
|
||||
- [The XOR Operator in Java](https://www.baeldung.com/java-xor-operator)
|
||||
- [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;
|
||||
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.Random;
|
||||
|
||||
public class RandomStringsUnitTest {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(RandomStringsUnitTest.class);
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenGeneratingRandomStringUnbounded_thenCorrect() {
|
||||
final byte[] array = new byte[7]; // length is bounded by 7
|
||||
new Random().nextBytes(array);
|
||||
final String generatedString = new String(array, Charset.forName("UTF-8"));
|
||||
|
||||
LOG.debug(generatedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenGeneratingRandomStringBounded_thenCorrect() {
|
||||
final int leftLimit = 97; // letter 'a'
|
||||
final int rightLimit = 122; // letter 'z'
|
||||
final int targetStringLength = 10;
|
||||
final Random random = new Random();
|
||||
final StringBuilder buffer = new StringBuilder(targetStringLength);
|
||||
|
||||
for (int i = 0; i < targetStringLength; i++) {
|
||||
final int randomLimitedInt = leftLimit + (int) (random.nextFloat() * (rightLimit - leftLimit + 1));
|
||||
buffer.append((char) randomLimitedInt);
|
||||
}
|
||||
final String generatedString = buffer.toString();
|
||||
|
||||
LOG.debug(generatedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingApache_whenGeneratingRandomString_thenCorrect() {
|
||||
final String generatedString = RandomStringUtils.random(10);
|
||||
|
||||
LOG.debug(generatedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingApache_whenGeneratingRandomAlphabeticString_thenCorrect() {
|
||||
final String generatedString = RandomStringUtils.randomAlphabetic(10);
|
||||
|
||||
LOG.debug(generatedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingApache_whenGeneratingRandomAlphanumericString_thenCorrect() {
|
||||
final String generatedString = RandomStringUtils.randomAlphanumeric(10);
|
||||
|
||||
LOG.debug(generatedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingApache_whenGeneratingRandomStringBounded_thenCorrect() {
|
||||
final int length = 10;
|
||||
final boolean useLetters = true;
|
||||
final boolean useNumbers = false;
|
||||
final String generatedString = RandomStringUtils.random(length, useLetters, useNumbers);
|
||||
|
||||
LOG.debug(generatedString);
|
||||
}
|
||||
|
||||
}
|
||||
package com.baeldung.randomstrings;
|
||||
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.Random;
|
||||
|
||||
public class RandomStringsUnitTest {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(RandomStringsUnitTest.class);
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenGeneratingRandomStringUnbounded_thenCorrect() {
|
||||
byte[] array = new byte[7]; // length is bounded by 7
|
||||
new Random().nextBytes(array);
|
||||
String generatedString = new String(array, Charset.forName("UTF-8"));
|
||||
|
||||
LOG.debug(generatedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenGeneratingRandomStringBounded_thenCorrect() {
|
||||
int leftLimit = 97; // letter 'a'
|
||||
int rightLimit = 122; // letter 'z'
|
||||
int targetStringLength = 10;
|
||||
Random random = new Random();
|
||||
StringBuilder buffer = new StringBuilder(targetStringLength);
|
||||
|
||||
for (int i = 0; i < targetStringLength; i++) {
|
||||
int randomLimitedInt = leftLimit + (int) (random.nextFloat() * (rightLimit - leftLimit + 1));
|
||||
buffer.append((char) randomLimitedInt);
|
||||
}
|
||||
String generatedString = buffer.toString();
|
||||
|
||||
LOG.debug(generatedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingJava8_whenGeneratingRandomAlphabeticString_thenCorrect() {
|
||||
int leftLimit = 97; // letter 'a'
|
||||
int rightLimit = 122; // letter 'z'
|
||||
int targetStringLength = 10;
|
||||
Random random = new Random();
|
||||
|
||||
String generatedString = random.ints(leftLimit, rightLimit + 1)
|
||||
.limit(targetStringLength)
|
||||
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
|
||||
.toString();
|
||||
|
||||
LOG.debug(generatedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingJava8_whenGeneratingRandomAlphanumericString_thenCorrect() {
|
||||
int leftLimit = 48; // numeral '0'
|
||||
int rightLimit = 122; // letter 'z'
|
||||
int targetStringLength = 10;
|
||||
Random random = new Random();
|
||||
|
||||
String generatedString = random.ints(leftLimit, rightLimit + 1)
|
||||
.filter(i -> (i <= 57 || i >= 65) && (i <= 90 || i >= 97))
|
||||
.limit(targetStringLength)
|
||||
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
|
||||
.toString();
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -14,6 +14,19 @@
|
||||
<relativePath>../../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>${jmh-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${jmh-core.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-text</finalName>
|
||||
<resources>
|
||||
|
@ -0,0 +1,92 @@
|
||||
package com.baeldung.patternreuse;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
import org.openjdk.jmh.infra.Blackhole;
|
||||
import org.openjdk.jmh.runner.RunnerException;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.MILLISECONDS)
|
||||
@Fork(value = 1, warmups = 1)
|
||||
@Warmup(iterations = 5)
|
||||
@State(Scope.Benchmark)
|
||||
public class PatternPerformanceComparison {
|
||||
|
||||
private static final String PATTERN = "\\d*[02468]";
|
||||
private static List<String> values;
|
||||
|
||||
private static Matcher matcherFromPreCompiledPattern;
|
||||
private static Pattern preCompiledPattern;
|
||||
|
||||
public static void main(String[] args) throws IOException, RunnerException {
|
||||
org.openjdk.jmh.Main.main(args);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void matcherFromPreCompiledPatternResetMatches(Blackhole bh) {
|
||||
//With pre-compiled pattern and reusing the matcher
|
||||
// 1 Pattern object created
|
||||
// 1 Matcher objects created
|
||||
for (String value : values) {
|
||||
bh.consume(matcherFromPreCompiledPattern.reset(value).matches());
|
||||
}
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void preCompiledPatternMatcherMatches(Blackhole bh) {
|
||||
// With pre-compiled pattern
|
||||
// 1 Pattern object created
|
||||
// 5_000_000 Matcher objects created
|
||||
for (String value : values) {
|
||||
bh.consume(preCompiledPattern.matcher(value).matches());
|
||||
}
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void patternCompileMatcherMatches(Blackhole bh) {
|
||||
// Above approach "Pattern.matches(PATTERN, value)" makes this internally
|
||||
// 5_000_000 Pattern objects created
|
||||
// 5_000_000 Matcher objects created
|
||||
for (String value : values) {
|
||||
bh.consume(Pattern.compile(PATTERN).matcher(value).matches());
|
||||
}
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void patternMatches(Blackhole bh) {
|
||||
// Above approach "value.matches(PATTERN)" makes this internally
|
||||
// 5_000_000 Pattern objects created
|
||||
// 5_000_000 Matcher objects created
|
||||
for (String value : values) {
|
||||
bh.consume(Pattern.matches(PATTERN, value));
|
||||
}
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void stringMatchs(Blackhole bh) {
|
||||
// 5_000_000 Pattern objects created
|
||||
// 5_000_000 Matcher objects created
|
||||
Instant start = Instant.now();
|
||||
for (String value : values) {
|
||||
bh.consume(value.matches(PATTERN));
|
||||
}
|
||||
}
|
||||
|
||||
@Setup()
|
||||
public void setUp() {
|
||||
preCompiledPattern = Pattern.compile(PATTERN);
|
||||
matcherFromPreCompiledPattern = preCompiledPattern.matcher("");
|
||||
|
||||
values = new ArrayList<>();
|
||||
for (int x = 1; x <= 5_000_000; x++) {
|
||||
values.add(String.valueOf(x));
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,63 @@
|
||||
package com.baeldung.patternreuse;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class PatternUnitTest {
|
||||
|
||||
private static final Pattern FIRST_LAST_NAME_PRE_COMPILED_PATTERN = Pattern.compile("[a-zA-Z]{3,} [a-zA-Z]{3,}");
|
||||
private static final Pattern SPLIT_PRE_COMPILED_PATTERN = Pattern.compile("__");
|
||||
|
||||
@Test
|
||||
public void givenPreCompiledPattern_whenCallMatcher_thenReturnAMatcherToMatches() {
|
||||
Matcher matcherName1 = FIRST_LAST_NAME_PRE_COMPILED_PATTERN.matcher("Fabio Silva");
|
||||
Matcher matcherName2 = FIRST_LAST_NAME_PRE_COMPILED_PATTERN.matcher("Mr. Silva");
|
||||
|
||||
boolean matchesName1 = matcherName1.matches();
|
||||
boolean matchesName2 = matcherName2.matches();
|
||||
|
||||
assertTrue(matchesName1);
|
||||
assertFalse(matchesName2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPreCompiledPattern_whenCallAsPredicate_thenReturnPredicateToFindPatternInTheList() {
|
||||
List<String> namesToValidate = Arrays.asList("Fabio Silva", "Mr. Silva");
|
||||
Predicate<String> patternsAsPredicate = FIRST_LAST_NAME_PRE_COMPILED_PATTERN.asPredicate();
|
||||
|
||||
List<String> validNames = namesToValidate.stream()
|
||||
.filter(patternsAsPredicate)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertEquals(1, validNames.size());
|
||||
assertTrue(validNames.contains("Fabio Silva"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPreCompiledPattern_whenCallSplit_thenReturnArrayWithValuesSplitByThePattern() {
|
||||
String[] textSplit = SPLIT_PRE_COMPILED_PATTERN.split("My_Name__is__Fabio_Silva");
|
||||
|
||||
assertEquals("My_Name", textSplit[0]);
|
||||
assertEquals("is", textSplit[1]);
|
||||
assertEquals("Fabio_Silva", textSplit[2]);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPreCompiledPattern_whenCallSplitAsStream_thenReturnArraySplitByThePattern() {
|
||||
Stream<String> textSplitAsStream = SPLIT_PRE_COMPILED_PATTERN.splitAsStream("My_Name__is__Fabio_Silva");
|
||||
String[] textSplit = textSplitAsStream.toArray(String[]::new);
|
||||
|
||||
assertEquals("My_Name", textSplit[0]);
|
||||
assertEquals("is", textSplit[1]);
|
||||
assertEquals("Fabio_Silva", textSplit[2]);
|
||||
}
|
||||
}
|
@ -82,3 +82,4 @@ The following guides may also be helpful:
|
||||
* https://spring.io/guides/gs/batch-processing/[Creating a Batch Service]
|
||||
|
||||
include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/master/footer.adoc[]
|
||||
|
||||
|
@ -8,22 +8,11 @@
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<artifactId>jackson-modules</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>
|
@ -8,23 +8,11 @@
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<artifactId>jackson-modules</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>
|
||||
<!--jackson for xml -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.dataformat</groupId>
|
||||
<artifactId>jackson-dataformat-xml</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<!-- YAML -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.dataformat</groupId>
|
@ -8,17 +8,11 @@
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<artifactId>jackson-modules</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.datatype</groupId>
|
||||
<artifactId>jackson-datatype-joda</artifactId>
|
||||
@ -29,12 +23,6 @@
|
||||
<artifactId>jackson-datatype-jsr310</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>
|
||||
</dependencies>
|
||||
|
||||
<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