Merge remote-tracking branch 'origin/master'

This commit is contained in:
alexandru.borza
2023-05-12 20:11:37 +03:00
550 changed files with 9153 additions and 3906 deletions
+1
View File
@@ -12,3 +12,4 @@ This module contains articles about Java 14.
- [Java 14 Record Keyword](https://www.baeldung.com/java-record-keyword)
- [New Features in Java 14](https://www.baeldung.com/java-14-new-features)
- [Java 14 Record vs. Lombok](https://www.baeldung.com/java-record-vs-lombok)
- [Record vs. Final Class in Java](https://www.baeldung.com/java-record-vs-final-class)
@@ -0,0 +1,18 @@
package com.baeldung.java14.recordvsfinal;
public record USCitizen(String firstName, String lastName, String address) {
static int countryCode;
// static initializer
static {
countryCode = 1;
}
public static int getCountryCode() {
return countryCode;
}
public String getFullName() {
return firstName + " " + lastName;
}
}
@@ -0,0 +1,26 @@
package com.baeldung.java14.recordvsfinal;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class USCitizenUnitTest {
@Test
public void givenName_whenGetNameAndCode_thenExpectedValuesReturned() {
String firstName = "Joan";
String lastName = "Winn";
String address = "1892 Black Stallion Road";
int countryCode = 1;
USCitizen citizen = new USCitizen(firstName, lastName, address);
assertEquals(firstName + " " + lastName, citizen.getFullName());
assertEquals(countryCode, USCitizen.getCountryCode());
}
}
@@ -0,0 +1,40 @@
package com.baeldung.java8to17;
public class Address {
private String street;
private String city;
private String pin;
public Address(String street, String city, String pin) {
super();
this.street = street;
this.city = city;
this.pin = pin;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getPin() {
return pin;
}
public void setPin(String pin) {
this.pin = pin;
}
}
@@ -0,0 +1,4 @@
package com.baeldung.java8to17;
public record Circle(double radius) implements Shape {
}
@@ -0,0 +1,30 @@
package com.baeldung.java8to17;
public class Person {
private String name;
private Address address;
public Person(String name, Address address) {
super();
this.name = name;
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
@@ -0,0 +1,4 @@
package com.baeldung.java8to17;
public record Rectangle(double length, double width) implements Shape {
}
@@ -0,0 +1,5 @@
package com.baeldung.java8to17;
public interface Shape {
}
@@ -0,0 +1,5 @@
package com.baeldung.java8to17;
public record Student(int rollNo, String name) {
}
@@ -0,0 +1,87 @@
package com.baeldung.java17;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertThrows;
import java.util.Arrays;
import org.junit.jupiter.api.Test;
import com.baeldung.java8to17.Address;
import com.baeldung.java8to17.Circle;
import com.baeldung.java8to17.Person;
import com.baeldung.java8to17.Rectangle;
import com.baeldung.java8to17.Student;
public class Java8to17ExampleUnitTest {
@Test
void givenMultiLineText_whenUsingTextBlock_thenStringIsReturned() {
String value = """
This is a
Multi-line
Text
""";
assertThat(value).isEqualTo("This is a\nMulti-line\nText\n");
}
@Test
void givenString_whenUsingUtilFunctions_thenReturnsExpectedResult() {
assertThat(" ".isBlank());
assertThat("Twinkle ".repeat(2)).isEqualTo("Twinkle Twinkle ");
assertThat("Format Line".indent(4)).isEqualTo(" Format Line\n");
assertThat("Line 1 \n Line2".lines()).asList().size().isEqualTo(2);
assertThat(" Text with white spaces ".strip()).isEqualTo("Text with white spaces");
assertThat("Car, Bus, Train".transform(s1 -> Arrays.asList(s1.split(","))).get(0)).isEqualTo("Car");
}
@Test
void givenDataModel_whenUsingRecordType_thenBehavesLikeDTO() {
Student student = new Student(10, "Priya");
Student student2 = new Student(10, "Priya");
assertThat(student.rollNo()).isEqualTo(10);
assertThat(student.name()).isEqualTo("Priya");
assertThat(student.equals(student2));
assertThat(student.hashCode()).isEqualTo(student2.hashCode());
}
@Test
void givenObject_whenThrowingNPE_thenReturnsHelpfulMessage() {
Person student = new Person("Lakshmi", new Address("35, West Street", null, null));
Exception exception = assertThrows(NullPointerException.class, () -> {
student.getAddress().getCity().toLowerCase();
});
assertThat(exception.getMessage()).isEqualTo(
"Cannot invoke \"String.toLowerCase()\" because the return value of \"com.baeldung.java8to17.Address.getCity()\" is null");
}
@Test
void givenGenericObject_whenUsingPatternMatching_thenReturnsTargetType() {
String city = null;
Object obj = new Address("35, West Street", "Chennai", "6000041");
if (obj instanceof Address address) {
city = address.getCity();
}
assertThat(city).isEqualTo("Chennai");
}
@Test
void givenGenericObject_whenUsingSwitchExpression_thenPatternMatchesRightObject() {
Object shape = new Rectangle(10, 20);
double circumference = switch (shape) {
case Rectangle r -> 2 * r.length() + 2 * r.width();
case Circle c -> 2 * c.radius() * Math.PI;
default -> throw new IllegalArgumentException("Unknown shape");
};
assertThat(circumference).isEqualTo(60);
}
}
@@ -0,0 +1,19 @@
package com.baeldung.argsVsvarargs;
public class StringArrayAndVarargs {
public static void capitalizeNames(String[] args) {
for(int i = 0; i < args.length; i++){
args[i] = args[i].toUpperCase();
}
}
public static String[] firstLetterOfWords(String... args) {
String[] firstLetter = new String[args.length];
for(int i = 0; i < args.length; i++){
firstLetter[i] = String.valueOf(args[i].charAt(0));
}
return firstLetter;
}
}
@@ -0,0 +1,24 @@
package com.baeldung.argsVsvarargs;
import static com.baeldung.argsVsvarargs.StringArrayAndVarargs.capitalizeNames;
import static com.baeldung.argsVsvarargs.StringArrayAndVarargs.firstLetterOfWords;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class StringArrayAndVarargsUnitTest {
@Test
void whenCheckingArgumentClassName_thenNameShouldBeStringArray() {
String[] names = {"john", "ade", "kofi", "imo"};
assertNotNull(names);
assertEquals("java.lang.String[]", names.getClass().getTypeName());
capitalizeNames(names);
}
@Test
void whenCheckingReturnedObjectClass_thenClassShouldBeStringArray() {
assertEquals(String[].class, firstLetterOfWords("football", "basketball", "volleyball").getClass());
assertEquals(3, firstLetterOfWords("football", "basketball", "volleyball").length);
}
}
@@ -0,0 +1,78 @@
package com.baeldung.array.isobjectarray;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.lang.reflect.Array;
import org.junit.jupiter.api.Test;
public class CheckObjectIsArrayUnitTest {
private static final Object ARRAY_INT = new int[] { 1, 2, 3, 4, 5 };
private static final Object ARRAY_PERSON = new Person[] { new Person("Jackie Chan", "Hong Kong"), new Person("Tom Hanks", "United States") };
boolean isArray(Object obj) {
return obj instanceof Object[] || obj instanceof boolean[] || obj instanceof byte[] || obj instanceof short[] || obj instanceof char[] || obj instanceof int[] || obj instanceof long[] || obj instanceof float[] || obj instanceof double[];
}
@Test
void givenAnArrayObject_whenUsingInstanceof_getExpectedResult() {
assertTrue(ARRAY_PERSON instanceof Object[]);
assertFalse(ARRAY_INT instanceof Object[]);
assertTrue(ARRAY_INT instanceof int[]);
}
@Test
void givenAnArrayObject_whenUsingOurIsArray_getExpectedResult() {
assertTrue(isArray(ARRAY_PERSON));
assertTrue(isArray(ARRAY_INT));
}
@Test
void givenAnArrayObject_whenUsingClassIsArray_getExpectedResult() {
assertTrue(ARRAY_INT.getClass()
.isArray());
assertTrue(ARRAY_PERSON.getClass()
.isArray());
assertEquals(Person.class, ARRAY_PERSON.getClass()
.getComponentType());
assertEquals(int.class, ARRAY_INT.getClass()
.getComponentType());
}
@Test
void givenAnArrayObject_whenUsingArrayGet_getExpectedElement() {
if (ARRAY_PERSON.getClass()
.isArray() && ARRAY_PERSON.getClass()
.getComponentType() == Person.class) {
Person person = (Person) Array.get(ARRAY_PERSON, 1);
assertEquals("Tom Hanks", person.getName());
}
if (ARRAY_INT.getClass()
.isArray() && ARRAY_INT.getClass()
.getComponentType() == int.class) {
assertEquals(2, ((int) Array.get(ARRAY_INT, 1)));
}
}
}
class Person {
private String name;
private String Location;
public Person(String name, String location) {
this.name = name;
this.Location = location;
}
public String getName() {
return name;
}
public String getLocation() {
return Location;
}
}
@@ -0,0 +1,7 @@
=========
## Core Java Collections Cookbooks and Examples
### Relevant Articles:
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-4)
@@ -0,0 +1,58 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-collections-5</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>core-java-collections-5</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit-platform.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.roaringbitmap</groupId>
<artifactId>RoaringBitmap</artifactId>
<version>${roaringbitmap.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh.version}</version>
</dependency>
</dependencies>
<properties>
<junit.version>5.9.2</junit.version>
<roaringbitmap.version>0.9.38</roaringbitmap.version>
<jmh.version>1.36</jmh.version>
</properties>
</project>
@@ -0,0 +1,82 @@
package com.baeldung.roaringbitmap;
import java.util.BitSet;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.roaringbitmap.RoaringBitmap;
@State(Scope.Thread)
public class BitSetsBenchmark {
private RoaringBitmap rb1;
private BitSet bs1;
private RoaringBitmap rb2;
private BitSet bs2;
private final static int SIZE = 10_000_000;
@Setup
public void setup() {
rb1 = new RoaringBitmap();
bs1 = new BitSet(SIZE);
rb2 = new RoaringBitmap();
bs2 = new BitSet(SIZE);
for (int i = 0; i < SIZE / 2; i++) {
rb1.add(i);
bs1.set(i);
}
for (int i = SIZE / 2; i < SIZE; i++) {
rb2.add(i);
bs2.set(i);
}
}
@Benchmark
public RoaringBitmap roaringBitmapUnion() {
return RoaringBitmap.or(rb1, rb2);
}
@Benchmark
public BitSet bitSetUnion() {
BitSet result = (BitSet) bs1.clone();
result.or(bs2);
return result;
}
@Benchmark
public RoaringBitmap roaringBitmapIntersection() {
return RoaringBitmap.and(rb1, rb2);
}
@Benchmark
public BitSet bitSetIntersection() {
BitSet result = (BitSet) bs1.clone();
result.and(bs2);
return result;
}
@Benchmark
public RoaringBitmap roaringBitmapDifference() {
return RoaringBitmap.andNot(rb1, rb2);
}
@Benchmark
public BitSet bitSetDifference() {
BitSet result = (BitSet) bs1.clone();
result.andNot(bs2);
return result;
}
@Benchmark
public RoaringBitmap roaringBitmapXOR() {
return RoaringBitmap.xor(rb1, rb2);
}
@Benchmark
public BitSet bitSetXOR() {
BitSet result = (BitSet) bs1.clone();
result.xor(bs2);
return result;
}
}
@@ -0,0 +1,9 @@
package com.baeldung.roaringbitmap;
import java.io.IOException;
public class BitSetsBenchmarkRunner {
public static void main(String... args) throws IOException {
org.openjdk.jmh.Main.main(args);
}
}
@@ -0,0 +1,45 @@
package com.baeldung.roaringbitmap;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.roaringbitmap.RoaringBitmap;
class RoaringBitmapBenchmarkUnitTest {
@Test
public void givenTwoRoaringBitmap_whenUsingOr_thenWillGetSetsUnion() {
RoaringBitmap expected = RoaringBitmap.bitmapOf(1, 2, 3, 4, 5, 6, 7, 8);
RoaringBitmap A = RoaringBitmap.bitmapOf(1, 2, 3, 4, 5);
RoaringBitmap B = RoaringBitmap.bitmapOf(4, 5, 6, 7, 8);
RoaringBitmap union = RoaringBitmap.or(A, B);
assertEquals(expected, union);
}
@Test
public void givenTwoRoaringBitmap_whenUsingAnd_thenWillGetSetsIntersection() {
RoaringBitmap expected = RoaringBitmap.bitmapOf(4, 5);
RoaringBitmap A = RoaringBitmap.bitmapOfRange(1, 6);
RoaringBitmap B = RoaringBitmap.bitmapOf(4, 5, 6, 7, 8);
RoaringBitmap intersection = RoaringBitmap.and(A, B);
assertEquals(expected, intersection);
}
@Test
public void givenTwoRoaringBitmap_whenUsingAndNot_thenWillGetSetsDifference() {
RoaringBitmap expected = RoaringBitmap.bitmapOf(1, 2, 3);
RoaringBitmap A = new RoaringBitmap();
A.add(1L, 6L);
RoaringBitmap B = RoaringBitmap.bitmapOf(4, 5, 6, 7, 8);
RoaringBitmap difference = RoaringBitmap.andNot(A, B);
assertEquals(expected, difference);
}
@Test
public void givenTwoRoaringBitmap_whenUsingXOR_thenWillGetSetsSymmetricDifference() {
RoaringBitmap expected = RoaringBitmap.bitmapOf(1, 2, 3, 6, 7, 8);
RoaringBitmap A = RoaringBitmap.bitmapOfRange(1, 6);
RoaringBitmap B = RoaringBitmap.bitmapOfRange(4, 9);
RoaringBitmap xor = RoaringBitmap.xor(A, B);
assertEquals(expected, xor);
}
}
@@ -12,3 +12,4 @@ This module contains articles about the Java ArrayList collection
- [Case-Insensitive Searching in ArrayList](https://www.baeldung.com/java-arraylist-case-insensitive-search)
- [Storing Data Triple in a List in Java](https://www.baeldung.com/java-list-storing-triple)
- [Convert an ArrayList of Object to an ArrayList of String Elements](https://www.baeldung.com/java-object-list-to-strings)
- [Initialize an ArrayList with Zeroes or Null in Java](https://www.baeldung.com/java-arraylist-with-zeroes-or-null)
@@ -0,0 +1,62 @@
package com.baeldung.combine2liststomap;
import static java.lang.Math.min;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.jupiter.api.Test;
public class CombineTwoListsInAMapUnitTest {
private static final List<String> KEY_LIST = Arrays.asList("Number One", "Number Two", "Number Three", "Number Four", "Number Five");
private static final List<Integer> VALUE_LIST = Arrays.asList(1, 2, 3, 4, 5);
private static final Map<String, Integer> EXPECTED_MAP = new HashMap<String, Integer>() {{
put("Number One", 1);
put("Number Two", 2);
put("Number Three", 3);
put("Number Four", 4);
put("Number Five", 5);
}};
@Test
void givenTwoLists_whenUsingLoopAndListGet_shouldGetExpectedMap() {
Map<String, Integer> result = new HashMap<>();
int size = KEY_LIST.size();
if (KEY_LIST.size() != VALUE_LIST.size()) {
// throw an exception or print a warning
size = min(KEY_LIST.size(), VALUE_LIST.size());
}
for (int i = 0; i < size; i++) {
result.put(KEY_LIST.get(i), VALUE_LIST.get(i));
}
assertEquals(EXPECTED_MAP, result);
}
@Test
void givenTwoLists_whenUsingStreamApiAndListGet_shouldGetExpectedMap() {
Map<String, Integer> result = IntStream.range(0, KEY_LIST.size())
.boxed()
.collect(Collectors.toMap(KEY_LIST::get, VALUE_LIST::get));
assertEquals(EXPECTED_MAP, result);
}
@Test
void givenTwoLists_whenUsingIterators_shouldGetExpectedMap() {
Map<String, Integer> result = new HashMap<>();
Iterator<String> ik = KEY_LIST.iterator();
Iterator<Integer> iv = VALUE_LIST.iterator();
while (ik.hasNext() && iv.hasNext()) {
result.put(ik.next(), iv.next());
}
assertEquals(EXPECTED_MAP, result);
}
}
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<artifactId>core-java-collections-maps-6</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-collections-maps-6</name>
<packaging>jar</packaging>
<parent>
<artifactId>core-java-modules</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<properties>
<spring.version>5.2.5.RELEASE</spring.version>
</properties>
</project>
@@ -0,0 +1,47 @@
package com.baeldung.map.hashmapcopy;
import java.util.Map;
import com.google.common.collect.MapDifference;
import com.google.common.collect.Maps;
public class CopyingAHashMapToAnother {
public Map<String, String> copyByIteration(Map<String, String> sourceMap, Map<String, String> targetMap) {
for (Map.Entry<String, String> entry : sourceMap.entrySet()) {
if (!targetMap.containsKey(entry.getKey())) {
targetMap.put(entry.getKey(), entry.getValue());
}
}
return targetMap;
}
public Map<String, String> copyUsingPutAll(Map<String, String> sourceMap, Map<String, String> targetMap) {
sourceMap.keySet()
.removeAll(targetMap.keySet());
targetMap.putAll(sourceMap);
return targetMap;
}
public Map<String, String> copyUsingPutIfAbsent(Map<String, String> sourceMap, Map<String, String> targetMap) {
for (Map.Entry<String, String> entry : sourceMap.entrySet()) {
targetMap.putIfAbsent(entry.getKey(), entry.getValue());
}
return targetMap;
}
public Map<String, String> copyUsingPutIfAbsentForEach(Map<String, String> sourceMap, Map<String, String> targetMap) {
sourceMap.forEach(targetMap::putIfAbsent);
return targetMap;
}
public Map<String, String> copyUsingMapMerge(Map<String, String> sourceMap, Map<String, String> targetMap) {
sourceMap.forEach((key, value) -> targetMap.merge(key, value, (oldVal, newVal) -> oldVal));
return targetMap;
}
public Map<String, String> copyUsingGuavaMapDifference(Map<String, String> sourceMap, Map<String, String> targetMap) {
MapDifference<String, String> differenceMap = Maps.difference(sourceMap, targetMap);
targetMap.putAll(differenceMap.entriesOnlyOnLeft());
return targetMap;
}
}
@@ -0,0 +1,68 @@
package com.baeldung.map.hashmapcopy;
import java.util.HashMap;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import com.baeldung.map.hashmapcopy.CopyingAHashMapToAnother;
public class CopyHashMapIntoAnotherUnitTest {
@Test
public void givenSourceAndTargetMapsWhenIteratedOverThenCopyingSuccess(){
CopyingAHashMapToAnother obj = new CopyingAHashMapToAnother();
Assert.assertEquals(generateExpectedResultMap(), obj.copyByIteration(generateSourceMap(), generateTargetMap()));
}
@Test
public void givenSourceAndTargetMapsWhenUsedPutAllThenCopyingSuccess(){
CopyingAHashMapToAnother obj = new CopyingAHashMapToAnother();
Assert.assertEquals(generateExpectedResultMap(), obj.copyUsingPutAll(generateSourceMap(), generateTargetMap()));
}
@Test
public void givenSourceAndTargetMapsWhenUsedPutIfAbsentThenCopyingSuccess(){
CopyingAHashMapToAnother obj = new CopyingAHashMapToAnother();
Assert.assertEquals(generateExpectedResultMap(), obj.copyUsingPutIfAbsent(generateSourceMap(), generateTargetMap()));
Assert.assertEquals(generateExpectedResultMap(), obj.copyUsingPutIfAbsentForEach(generateSourceMap(), generateTargetMap()));
}
@Test
public void givenSourceAndTargetMapsWhenUsedMapMergeThenCopyingSuccess(){
CopyingAHashMapToAnother obj = new CopyingAHashMapToAnother();
Assert.assertEquals(generateExpectedResultMap(), obj.copyUsingMapMerge(generateSourceMap(), generateTargetMap()));
}
@Test
public void givenSourceAndTargetMapsWhenMapDifferenceUsedThenCopyingSuccess(){
CopyingAHashMapToAnother obj = new CopyingAHashMapToAnother();
Assert.assertEquals(generateExpectedResultMap(), obj.copyUsingGuavaMapDifference(generateSourceMap(), generateTargetMap()));
}
private Map<String, String> generateSourceMap(){
Map<String, String> sourceMap = new HashMap<>();
sourceMap.put("India", "Delhi");
sourceMap.put("United States", "Washington D.C.");
sourceMap.put("United Kingdom", "London DC");
return sourceMap;
}
private Map<String, String> generateTargetMap(){
Map<String, String> targetMap = new HashMap<>();
targetMap.put("Zimbabwe", "Harare");
targetMap.put("Norway", "Oslo");
targetMap.put("United Kingdom", "London");
return targetMap;
}
private Map<String, String> generateExpectedResultMap(){
Map<String, String> resultMap = new HashMap<>();
resultMap.put("India", "Delhi");
resultMap.put("United States", "Washington D.C.");
resultMap.put("United Kingdom", "London");
resultMap.put("Zimbabwe", "Harare");
resultMap.put("Norway", "Oslo");
return resultMap;
}
}
@@ -1,7 +1,7 @@
package com.baeldung.concurrent.atomic;
public class SafeCounterWithLock {
private volatile int counter;
private int counter;
int getValue() {
return counter;
@@ -10,12 +10,6 @@ public class SafeCounterWithoutLock {
}
void increment() {
while(true) {
int existingValue = getValue();
int newValue = existingValue + 1;
if(counter.compareAndSet(existingValue, newValue)) {
return;
}
}
counter.incrementAndGet();
}
}
@@ -17,8 +17,8 @@ public class ThreadSafeCounterIntegrationTest {
SafeCounterWithLock safeCounter = new SafeCounterWithLock();
IntStream.range(0, 1000)
.forEach(count -> service.submit(safeCounter::increment));
service.awaitTermination(100, TimeUnit.MILLISECONDS);
.forEach(count -> service.execute(safeCounter::increment));
shutdownAndAwaitTermination(service);
assertEquals(1000, safeCounter.getValue());
}
@@ -29,10 +29,30 @@ public class ThreadSafeCounterIntegrationTest {
SafeCounterWithoutLock safeCounter = new SafeCounterWithoutLock();
IntStream.range(0, 1000)
.forEach(count -> service.submit(safeCounter::increment));
service.awaitTermination(100, TimeUnit.MILLISECONDS);
.forEach(count -> service.execute(safeCounter::increment));
shutdownAndAwaitTermination(service);
assertEquals(1000, safeCounter.getValue());
}
private void shutdownAndAwaitTermination(ExecutorService pool) {
// Disable new tasks from being submitted
pool.shutdown();
try {
// Wait a while for existing tasks to terminate
if (!pool.awaitTermination(100, TimeUnit.MILLISECONDS)) {
// Cancel currently executing tasks forcefully
pool.shutdownNow();
// Wait a while for tasks to respond to being cancelled
if (!pool.awaitTermination(100, TimeUnit.MILLISECONDS))
System.err.println("Pool did not terminate");
}
} catch (InterruptedException ex) {
// (Re-)Cancel if current thread also interrupted
pool.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
}
}
}
@@ -24,4 +24,16 @@
</resources>
</build>
<properties>
<awaitility.version>4.2.0</awaitility.version>
</properties>
<dependencies>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>${awaitility.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,35 @@
package com.baeldung.concurrent;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class RequestProcessor {
private Map<String, String> requestStatuses = new HashMap<>();
public String processRequest() {
String requestId = UUID.randomUUID().toString();
requestStatuses.put(requestId, "PROCESSING");
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.schedule((() -> {
requestStatuses.put(requestId, "DONE");
}), getRandomNumberBetween(500, 2000), TimeUnit.MILLISECONDS);
return requestId;
}
public String getStatus(String requestId) {
return requestStatuses.get(requestId);
}
private int getRandomNumberBetween(int min, int max) {
Random random = new Random();
return random.nextInt(max - min) + min;
}
}
@@ -0,0 +1,41 @@
package com.baeldung.concurrent;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.concurrent.TimeUnit;
import org.awaitility.Awaitility;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
@DisplayName("Request processor")
public class RequestProcessorUnitTest {
RequestProcessor requestProcessor = new RequestProcessor();
@Test
@DisplayName("Wait for completion using Thread.sleep")
void whenWaitingWithThreadSleep_thenStatusIsDone() throws InterruptedException {
String requestId = requestProcessor.processRequest();
Thread.sleep(2000);
assertEquals("DONE", requestProcessor.getStatus(requestId));
}
@Test
@DisplayName("Wait for completion using Awaitility")
void whenWaitingWithAwaitility_thenStatusIsDone() {
String requestId = requestProcessor.processRequest();
Awaitility.await()
.atMost(2, TimeUnit.SECONDS)
.pollDelay(500, TimeUnit.MILLISECONDS)
.until(() -> requestProcessor.getStatus(requestId), not(equalTo("PROCESSING")));
assertEquals("DONE", requestProcessor.getStatus(requestId));
}
}
@@ -2,3 +2,4 @@
- [Functional Programming in Java](https://www.baeldung.com/java-functional-programming)
- [Functors in Java](https://www.baeldung.com/java-functors)
- [Callback Functions in Java](https://www.baeldung.com/java-callback-functions)
@@ -0,0 +1,2 @@
## Relevant Articles
- [Convert Hex to RGB Using Java](https://www.baeldung.com/java-convert-hex-to-rgb)
+25
View File
@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-hex</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-hex</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
</dependencies>
<properties>
</properties>
</project>
@@ -0,0 +1,25 @@
package com.baeldung.hextorgb;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class HexToRgbUnitTest {
@Test
public void givenHexCode_whenConvertedToRgb_thenCorrectRgbValuesAreReturned() {
String hexCode = "FF9933";
int red = 255;
int green = 153;
int blue = 51;
int resultRed = Integer.valueOf(hexCode.substring(0, 2), 16);
int resultGreen = Integer.valueOf(hexCode.substring(2, 4), 16);
int resultBlue = Integer.valueOf(hexCode.substring(4, 6), 16);
assertEquals(red, resultRed);
assertEquals(green, resultGreen);
assertEquals(blue, resultBlue);
}
}
@@ -5,3 +5,4 @@ This module contains articles about Java HttpClient
### Relevant articles
- [Posting with Java HttpClient](https://www.baeldung.com/java-httpclient-post)
- [Custom HTTP Header With the Java HttpClient](https://www.baeldung.com/java-http-client-custom-header)
- [Java HttpClient Connection Management](https://www.baeldung.com/java-httpclient-connection-management)
@@ -32,6 +32,12 @@
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock</artifactId>
<version>${wiremock.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
@@ -53,6 +59,7 @@
<maven.compiler.target.version>11</maven.compiler.target.version>
<assertj.version>3.22.0</assertj.version>
<mockserver.version>5.11.2</mockserver.version>
<wiremock.version>2.27.2</wiremock.version>
</properties>
</project>
@@ -0,0 +1,147 @@
package com.baeldung.httpclient.conn;
import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
import com.github.tomakehurst.wiremock.stubbing.ServeEvent;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;
import static java.net.URI.create;
public class HttpClientConnectionManagementUnitTest {
WireMockConfiguration firstConfiguration = WireMockConfiguration
.options()
.dynamicPort();
WireMockConfiguration secondConfiguration = WireMockConfiguration
.options()
.dynamicPort();
WireMockServer firstServer = new WireMockServer(firstConfiguration);
WireMockServer secondServer = new WireMockServer(secondConfiguration);
private String firstUrl;
private String secondUrl;
private HttpClient client = HttpClient.newHttpClient();
private HttpClient secondClient = HttpClient.newHttpClient();
private HttpRequest getRequest;
private HttpRequest secondGet;
@Before
public void setup() {
firstServer.start();
secondServer.start();
// add some request matchers
firstServer.stubFor(WireMock
.get(WireMock.anyUrl())
.willReturn(WireMock
.aResponse()
.withStatus(200)));
secondServer.stubFor(WireMock
.get(WireMock.anyUrl())
.willReturn(WireMock
.aResponse()
.withStatus(200)));
firstUrl = "http://localhost:" + firstServer.port() + "/first";
secondUrl = "http://localhost:" + secondServer.port() + "/second";
getRequest = HttpRequest
.newBuilder()
.uri(create(firstUrl))
.version(HttpClient.Version.HTTP_1_1)
.build();
secondGet = HttpRequest
.newBuilder()
.uri(create(secondUrl))
.version(HttpClient.Version.HTTP_1_1)
.build();
}
@After
public void tearDown() {
// display all the requests that the WireMock servers handled
List<ServeEvent> firstWiremockAllServeEvents = firstServer.getAllServeEvents();
List<ServeEvent> secondWiremockAllServeEvents = secondServer.getAllServeEvents();
firstWiremockAllServeEvents
.stream()
.map(event -> event
.getRequest()
.getAbsoluteUrl())
.forEach(System.out::println);
secondWiremockAllServeEvents
.stream()
.map(event -> event
.getRequest()
.getAbsoluteUrl())
.forEach(System.out::println);
// stop the WireMock servers
firstServer.stop();
secondServer.stop();
}
// Example 1. Use an HttpClient to connect to the same endpoint - reuses a connection from the internal pool
@Test
public final void givenAnHttpClient_whenTwoConnectionsToSameEndpointMadeSequentially_thenConnectionReused() throws InterruptedException, IOException {
// given two requests to the same destination
final HttpResponse<String> firstResponse = client.send(getRequest, HttpResponse.BodyHandlers.ofString());
final HttpResponse<String> secondResponse = client.send(getRequest, HttpResponse.BodyHandlers.ofString());
assert (firstResponse.statusCode() == 200) && (secondResponse.statusCode() == 200);
}
// Example 2. Use separate HttpClients to connect to the same endpoint - creates a connection per client
@Test
public final void givenTwoHttpClients_whenEachClientMakesConnectionSequentially_thenConnectionCreatedForEach() throws InterruptedException, IOException {
// given requests from two different client to same destination
final HttpResponse<String> firstResponse = client.send(getRequest, HttpResponse.BodyHandlers.ofString());
final HttpResponse<String> secondResponse = secondClient.send(getRequest, HttpResponse.BodyHandlers.ofString());
assert (firstResponse.statusCode() == 200) && (secondResponse.statusCode() == 200);
}
// Example 3. Use an HttpClient to Connect to first, second, then first endpoint again.
// New connections made each time when pool size is 1, or re-used when not restricted.
// Make sure to set the JVM arg when running the test:
// -Djdk.httpclient.connectionPoolSize=1
@Test
public final void givenAnHttpClientAndAPoolSizeOfOne_whenTwoConnectionsMadeBackToOriginal_thenFirstConnectionPurged() throws InterruptedException, IOException {
// given 3 requests, two to the first server and one to the second server
final HttpResponse<String> firstResponse = client.send(getRequest, HttpResponse.BodyHandlers.ofString());
final HttpResponse<String> secondResponse = client.send(secondGet, HttpResponse.BodyHandlers.ofString());
final HttpResponse<String> thirdResponse = client.send(getRequest, HttpResponse.BodyHandlers.ofString());
assert ((firstResponse.statusCode() == 200) && (secondResponse.statusCode() == 200) && (thirdResponse.statusCode() == 200));
}
// Example 4. Use an HttpClient to connect, wait for connection keepalive to pass, then connect again. New connection made for both calls.
// Make sure to set the JVM arg when running the test:
// -Djdk.httpclient.keepalive.timeout=2
@Test
public final void givenAnHttpClientAndConnectionKeepAliveOfTwoSeconds_whenCallMadeAfterKeepaliveExpires_thenNewConnection() throws InterruptedException, IOException {
// given 2 requests to the same destination with the second call made after the keepalive timeout has passed
final HttpResponse<String> firstResponse = client.send(getRequest, HttpResponse.BodyHandlers.ofString());
Thread.sleep(3000); // exceeds 2 seconds configured by JVM arg
final HttpResponse<String> secondResponse = client.send(getRequest, HttpResponse.BodyHandlers.ofString());
assert ((firstResponse.statusCode() == 200) && (secondResponse.statusCode() == 200));
}
}
@@ -0,0 +1,3 @@
org.eclipse.jetty.util.log.class=org.eclipse.jetty.util.log.StrErrLog
org.eclipse.jetty.LEVEL=DEBUG
jetty.logs=logs
@@ -0,0 +1,8 @@
package com.baeldung.reflection;
public class PrivateConstructorClass {
private PrivateConstructorClass() {
System.out.println("Used the private constructor!");
}
}
@@ -0,0 +1,17 @@
package com.baeldung.reflection;
import java.lang.reflect.Constructor;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class PrivateConstructorUnitTest {
@Test
public void whenConstructorIsPrivate_thenInstanceSuccess() throws Exception {
Constructor<PrivateConstructorClass> pcc = PrivateConstructorClass.class.getDeclaredConstructor();
pcc.setAccessible(true);
PrivateConstructorClass privateConstructorInstance = pcc.newInstance();
Assertions.assertTrue(privateConstructorInstance instanceof PrivateConstructorClass);
}
}
@@ -1,3 +1,4 @@
## Relevant Articles:
- [Difference Between URI.create() and new URI()](https://www.baeldung.com/java-uri-create-and-new-uri)
- [Validating URL in Java](https://www.baeldung.com/java-validate-url)
- [Validating URL in Java](https://www.baeldung.com/java-validate-url)
- [Validating IPv4 Address in Java](https://www.baeldung.com/java-validate-ipv4-address)
@@ -8,3 +8,4 @@
- [Creating Random Numbers With No Duplicates in Java](https://www.baeldung.com/java-unique-random-numbers)
- [Multiply a BigDecimal by an Integer in Java](https://www.baeldung.com/java-bigdecimal-multiply-integer)
- [Check if an Integer Value is null or Zero in Java](https://www.baeldung.com/java-check-integer-null-or-zero)
- [Return Absolute Difference of Two Integers in Java](https://www.baeldung.com/java-absolute-difference-of-two-integers)
@@ -16,7 +16,7 @@ public class BadPaddingExamples {
SecretKey encryptionKey = CryptoUtils.getKeyForText("BaeldungIsASuperCoolSite");
SecretKey differentKey = CryptoUtils.getKeyForText("ThisGivesUsAnAlternative");
Cipher cipher = Cipher.getInstance("AES/ECB/ISO10126Padding");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, encryptionKey);
byte[] cipherTextBytes = cipher.doFinal(plainTextBytes);
@@ -28,12 +28,12 @@ public class BadPaddingExamples {
public static byte[] encryptAndDecryptUsingDifferentAlgorithms(SecretKey key, IvParameterSpec ivParameterSpec,
byte[] plainTextBytes) throws InvalidKeyException, GeneralSecurityException {
Cipher cipher = Cipher.getInstance("AES/CBC/ISO10126Padding");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, ivParameterSpec);
byte[] cipherTextBytes = cipher.doFinal(plainTextBytes);
cipher = Cipher.getInstance("AES/ECB/ISO10126Padding");
cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key);
@@ -48,7 +48,7 @@ class AESUtilUnitTest implements WithAssertions {
IvParameterSpec ivParameterSpec = AESUtil.generateIv();
File inputFile = Paths.get("src/test/resources/baeldung.txt")
.toFile();
File encryptedFile = new File("classpath:baeldung.encrypted");
File encryptedFile = new File("baeldung.encrypted");
File decryptedFile = new File("document.decrypted");
// when
@@ -57,8 +57,8 @@ class AESUtilUnitTest implements WithAssertions {
// then
assertThat(inputFile).hasSameTextualContentAs(decryptedFile);
encryptedFile.delete();
decryptedFile.delete();
encryptedFile.deleteOnExit();
decryptedFile.deleteOnExit();
}
@Test
@@ -7,3 +7,5 @@
- [Finding Max Date in List Using Streams](https://www.baeldung.com/java-max-date-list-streams)
- [Batch Processing of Stream Data in Java](https://www.baeldung.com/java-stream-batch-processing)
- [Stream to Iterable in Java](https://www.baeldung.com/java-stream-to-iterable)
- [Understanding the Difference Between Stream.of() and IntStream.range()](https://www.baeldung.com/java-stream-of-and-intstream-range)
- [Check if Object Is an Array in Java](https://www.baeldung.com/java-check-if-object-is-an-array)
@@ -0,0 +1,43 @@
package com.baeldung.streams.intarraytostrings;
import java.util.Arrays;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class ArrayConversionUtils {
public static void createStreamExample() {
int[] intArray = { 1, 2, 3, 4, 5 };
IntStream intStream = Arrays.stream(intArray);
Integer[] integerArray = { 1, 2, 3, 4, 5 };
Stream<Integer> integerStream = Arrays.stream(integerArray);
}
public static String[] convertToStringArray(Integer[] input) {
return Arrays.stream(input)
.map(Object::toString)
.toArray(String[]::new);
}
public static String[] convertToStringArray(int[] input) {
return Arrays.stream(input)
.mapToObj(Integer::toString)
.toArray(String[]::new);
}
public static String[] convertToStringArrayWithBoxing(int[] input) {
return Arrays.stream(input)
.boxed()
.map(Object::toString)
.toArray(String[]::new);
}
public static String convertToString(int[] input){
return Arrays.stream(input)
.mapToObj(Integer::toString)
.collect(Collectors.joining(", "));
}
}
@@ -0,0 +1,52 @@
package com.baeldung.streams.intarraytostrings;
import static com.baeldung.streams.intarraytostrings.ArrayConversionUtils.convertToString;
import static com.baeldung.streams.intarraytostrings.ArrayConversionUtils.convertToStringArray;
import static com.baeldung.streams.intarraytostrings.ArrayConversionUtils.convertToStringArrayWithBoxing;
import org.junit.Assert;
import org.junit.Test;
public class IntArrayToStringUnitTest {
@Test
public void whenConvertingIntegers_thenHandleStreamOfIntegers() {
Integer[] integerNumbers = { 1, 2, 3, 4, 5 };
String[] expectedOutput = { "1", "2", "3", "4", "5" };
String[] strings = convertToStringArray(integerNumbers);
Assert.assertArrayEquals(expectedOutput, strings);
}
@Test
public void whenConvertingInts_thenHandleIntStream() {
int[] intNumbers = { 1, 2, 3, 4, 5 };
String[] expectedOutput = { "1", "2", "3", "4", "5" };
String[] strings = convertToStringArray(intNumbers);
Assert.assertArrayEquals(expectedOutput, strings);
}
@Test
public void givenAnIntArray_whenBoxingToInteger_thenHandleStreamOfIntegers() {
int[] intNumbers = { 1, 2, 3, 4, 5 };
String[] expectedOutput = { "1", "2", "3", "4", "5" };
String[] strings = convertToStringArrayWithBoxing(intNumbers);
Assert.assertArrayEquals(expectedOutput, strings);
}
@Test
public void givenAnIntArray_whenUsingCollectorsJoining_thenReturnCommaSeparatedString(){
int[] intNumbers = { 1, 2, 3, 4, 5 };
String expectedOutput = "1, 2, 3, 4, 5";
String string = convertToString(intNumbers);
Assert.assertEquals(expectedOutput, string);
}
}
@@ -0,0 +1,66 @@
package com.baeldung.streams.streamofvsintstream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
public class DiffBetweenStreamOfAndIntStreamRangeUnitTest {
@Test
void givenStreamOfAndIntStreamRange_whenPeekSortAndFirst_shouldResultDifferent() {
Stream<Integer> normalStream = Stream.of(1, 2, 3, 4, 5);
IntStream intStreamByRange = IntStream.range(1, 6);
List<Integer> normalStreamPeekResult = new ArrayList<>();
List<Integer> intStreamPeekResult = new ArrayList<>();
// First, the regular Stream
normalStream.peek(normalStreamPeekResult::add)
.sorted()
.findFirst();
assertEquals(Arrays.asList(1, 2, 3, 4, 5), normalStreamPeekResult);
// Then, the IntStream
intStreamByRange.peek(intStreamPeekResult::add)
.sorted()
.findFirst();
assertEquals(Arrays.asList(1), intStreamPeekResult);
}
@Test
void givenStream_whenPeekAndFirst_shouldHaveOnlyFirstElement() {
Stream<Integer> normalStream = Stream.of(1, 2, 3, 4, 5);
IntStream intStreamByRange = IntStream.range(1, 6);
List<Integer> normalStreamPeekResult = new ArrayList<>();
List<Integer> intStreamPeekResult = new ArrayList<>();
// First, the regular Stream
normalStream.peek(normalStreamPeekResult::add)
.findFirst();
assertEquals(Arrays.asList(1), normalStreamPeekResult);
// Then, the IntStream
intStreamByRange.peek(intStreamPeekResult::add)
.findFirst();
assertEquals(Arrays.asList(1), intStreamPeekResult);
}
@Test
void givenSortedStream_whenPeekSortAndFirst_shouldOnlyHaveOneElement() {
List<String> peekResult = new ArrayList<>();
TreeSet<String> treeSet = new TreeSet<>(Arrays.asList("CCC", "BBB", "AAA", "DDD", "KKK"));
treeSet.stream()
.peek(peekResult::add)
.sorted()
.findFirst();
assertEquals(Arrays.asList("AAA"), peekResult);
}
}
@@ -9,3 +9,4 @@ This module contains articles about string-related algorithms.
- [Email Validation in Java](https://www.baeldung.com/java-email-validation-regex)
- [Check if the First Letter of a String is Uppercase](https://www.baeldung.com/java-check-first-letter-uppercase)
- [Find the First Non Repeating Character in a String in Java](https://www.baeldung.com/java-find-the-first-non-repeating-character)
- [Find the First Embedded Occurrence of an Integer in a Java String](https://www.baeldung.com/java-string-find-embedded-integer)
@@ -0,0 +1,18 @@
package com.baeldung.firstocurrenceofaninteger;
public class FirstOccurrenceOfAnInteger {
static Integer findFirstInteger(String s) {
int i = 0;
while (i < s.length() && !Character.isDigit(s.charAt(i))) {
i++;
}
int j = i;
while (j < s.length() && Character.isDigit(s.charAt(j))) {
j++;
}
return Integer.parseInt(s.substring(i, j));
}
}
@@ -0,0 +1,46 @@
package com.baeldung.firstocurrenceofaninteger;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
class FirstOccurrenceOfAnIntegerUnitTest {
@Test
void whenUsingPatternMatcher_findFirstInteger() {
String s = "ba31dung123";
Matcher matcher = Pattern.compile("\\d+").matcher(s);
matcher.find();
int i = Integer.parseInt(matcher.group());
Assertions.assertEquals(31, i);
}
@Test
void whenUsingScanner_findFirstInteger() {
int i = new Scanner("ba31dung123").useDelimiter("\\D+").nextInt();
Assertions.assertEquals(31, i);
}
@Test
void whenUsingSplit_findFirstInteger() {
String str = "ba31dung123";
List<String> tokens = Arrays.stream(str.split("\\D+"))
.filter(s -> s.length() > 0).collect(Collectors.toList());
Assertions.assertEquals(31, Integer.parseInt(tokens.get(0)));
}
@Test
void whenUsingCustomMethod_findFirstInteger() {
String str = "ba31dung123";
Integer i = FirstOccurrenceOfAnInteger.findFirstInteger(str);
Assertions.assertEquals(31, i);
}
}
@@ -3,12 +3,24 @@ package com.baeldung.timer;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Random;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
public class NewsletterTask extends TimerTask {
@Override
public void run() {
System.out.println("Email sent at: "
+ LocalDateTime.ofInstant(Instant.ofEpochMilli(scheduledExecutionTime()), ZoneId.systemDefault()));
Random random = new Random();
int value = random.ints(1, 7)
.findFirst()
.getAsInt();
System.out.println("The duration of sending the mail will took: " + value);
try {
TimeUnit.SECONDS.sleep(value);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
@@ -5,7 +5,7 @@ import org.junit.jupiter.api.Test;
import java.util.Timer;
class NewsletterTaskUnitTest {
class NewsletterTaskUnitManualTest {
private final Timer timer = new Timer();
@AfterEach
@@ -17,17 +17,13 @@ class NewsletterTaskUnitTest {
void givenNewsletterTask_whenTimerScheduledEachSecondFixedDelay_thenNewsletterSentEachSecond() throws Exception {
timer.schedule(new NewsletterTask(), 0, 1000);
for (int i = 0; i < 3; i++) {
Thread.sleep(1000);
}
Thread.sleep(20000);
}
@Test
void givenNewsletterTask_whenTimerScheduledEachSecondFixedRate_thenNewsletterSentEachSecond() throws Exception {
timer.scheduleAtFixedRate(new NewsletterTask(), 0, 1000);
for (int i = 0; i < 3; i++) {
Thread.sleep(1000);
}
Thread.sleep(20000);
}
}
+16 -1
View File
@@ -25,6 +25,21 @@
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>com.github.f4b6a3</groupId>
<artifactId>uuid-creator</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.uuid</groupId>
<artifactId>java-uuid-generator</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>com.github.f4b6a3</groupId>
<artifactId>tsid-creator</artifactId>
<version>5.2.3</version>
</dependency>
</dependencies>
<build>
@@ -143,4 +158,4 @@
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
</properties>
</project>
</project>
@@ -0,0 +1,42 @@
package com.baeldung.timebaseduuid;
import com.fasterxml.uuid.Generators;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
public class JavaUUIDCreatorBenchmark {
public static void main(String[] args) throws InterruptedException {
int threadCount = 128;
int iterationCount = 100_000;
Map<UUID, Long> uuidMap = new ConcurrentHashMap<>();
AtomicLong collisionCount = new AtomicLong();
long startNanos = System.nanoTime();
CountDownLatch endLatch = new CountDownLatch(threadCount);
for (long i = 0; i < threadCount; i++) {
long threadId = i;
new Thread(() -> {
for (long j = 0; j < iterationCount; j++) {
UUID uuid = Generators.timeBasedGenerator().generate();
Long existingUUID = uuidMap.put(uuid, (threadId * iterationCount) + j);
if(existingUUID != null) {
collisionCount.incrementAndGet();
}
}
endLatch.countDown();
}).start();
}
endLatch.await();
System.out.println(threadCount * iterationCount + " UUIDs generated, " + collisionCount + " collisions in "
+ TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos) + "ms");
}
}
@@ -0,0 +1,13 @@
package com.baeldung.timebaseduuid;
import com.fasterxml.uuid.Generators;
public class JavaUUIDCreatorExample {
public static void main(String[] args) {
System.out.println("UUID Version 1: " + Generators.timeBasedGenerator().generate());
System.out.println("UUID Version 6: " + Generators.timeBasedReorderedGenerator().generate());
System.out.println("UUID Version 7: " + Generators.timeBasedEpochGenerator().generate());
}
}
@@ -0,0 +1,42 @@
package com.baeldung.timebaseduuid;
import com.github.f4b6a3.uuid.UuidCreator;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
public class UUIDCreatorBenchmark {
public static void main(String[] args) throws InterruptedException {
int threadCount = 128;
int iterationCount = 100_000;
Map<UUID, Long> uuidMap = new ConcurrentHashMap<>();
AtomicLong collisionCount = new AtomicLong();
long startNanos = System.nanoTime();
CountDownLatch endLatch = new CountDownLatch(threadCount);
for (long i = 0; i < threadCount; i++) {
long threadId = i;
new Thread(() -> {
for (long j = 0; j < iterationCount; j++) {
UUID uuid = UuidCreator.getTimeBased();
Long existingUUID = uuidMap.put(uuid, (threadId * iterationCount) + j);
if(existingUUID != null) {
collisionCount.incrementAndGet();
}
}
endLatch.countDown();
}).start();
}
endLatch.await();
System.out.println(threadCount * iterationCount + " UUIDs generated, " + collisionCount + " collisions in "
+ TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos) + "ms");
}
}
@@ -0,0 +1,13 @@
package com.baeldung.timebaseduuid;
import com.github.f4b6a3.uuid.UuidCreator;
public class UUIDCreatorExample {
public static void main(String[] args) {
System.out.println("UUID Version 1: " + UuidCreator.getTimeBased());
System.out.println("UUID Version 6: " + UuidCreator.getTimeOrdered());
System.out.println("UUID Version 7: " + UuidCreator.getTimeOrderedEpoch());
}
}
+1
View File
@@ -10,3 +10,4 @@
- [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties)
- [Illegal Character Compilation Error](https://www.baeldung.com/java-illegal-character-error)
- [Lambda Expression vs. Anonymous Inner Class](https://www.baeldung.com/java-lambdas-vs-anonymous-class)
- [Difference Between Class.forName() and Class.forName().newInstance()](https://www.baeldung.com/java-class-forname-vs-class-forname-newinstance)
@@ -0,0 +1,8 @@
package com.baeldung.loadclass;
public class MyClassForLoad {
private String data = "some data";
}
@@ -0,0 +1,30 @@
package com.baeldung.loadclass;
import org.junit.jupiter.api.Test;
import java.lang.reflect.InvocationTargetException;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
public class LoadClassUnitTest {
@Test
public void whenUseClassForName_createdInstanceOfClassClass() throws ClassNotFoundException {
Class instance = Class.forName("com.baeldung.loadclass.MyClassForLoad");
assertInstanceOf(Class.class, instance, "instance should be of Class.class");
}
@Test
public void whenUseClassForNameWithNewInstance_createdInstanceOfTargetClas() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
Object instance = Class.forName("com.baeldung.loadclass.MyClassForLoad").newInstance();
assertInstanceOf(MyClassForLoad.class, instance, "instance should be of MyClassForLoad class");
}
@Test
public void whenUseClassForNameWithDeclaredConstructor_newInstanceCreatedInstanceOfTargetClas() throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
Object instance = Class.forName("com.baeldung.loadclass.MyClassForLoad").getDeclaredConstructor().newInstance();
assertInstanceOf(MyClassForLoad.class, instance, "instance should be of MyClassForLoad class");
}
}
+3
View File
@@ -31,6 +31,7 @@
<module>core-java-collections-2</module>
<module>core-java-collections-3</module>
<module>core-java-collections-4</module>
<module>core-java-collections-5</module>
<module>core-java-collections-conversions</module>
<module>core-java-collections-conversions-2</module>
<module>core-java-collections-set-2</module>
@@ -62,6 +63,7 @@
<module>core-java-exceptions-4</module>
<module>core-java-function</module>
<module>core-java-functional</module>
<module>core-java-hex</module>
<module>core-java-io</module>
<module>core-java-io-2</module>
<module>core-java-io-3</module>
@@ -131,6 +133,7 @@
<module>core-java-regex-2</module>
<module>core-java-uuid</module>
<module>pre-jpms</module>
<module>core-java-collections-maps-6</module>
</modules>
<dependencyManagement>