merge and fix conflict
This commit is contained in:
commit
8d11845d5b
@ -4,3 +4,4 @@
|
|||||||
- [Implementing Simple State Machines with Java Enums](https://www.baeldung.com/java-enum-simple-state-machine)
|
- [Implementing Simple State Machines with Java Enums](https://www.baeldung.com/java-enum-simple-state-machine)
|
||||||
- [Converting Between Roman and Arabic Numerals in Java](http://www.baeldung.com/java-convert-roman-arabic)
|
- [Converting Between Roman and Arabic Numerals in Java](http://www.baeldung.com/java-convert-roman-arabic)
|
||||||
- [Practical Java Examples of the Big O Notation](http://www.baeldung.com/java-algorithm-complexity)
|
- [Practical Java Examples of the Big O Notation](http://www.baeldung.com/java-algorithm-complexity)
|
||||||
|
- [Checking If a List Is Sorted in Java](https://www.baeldung.com/java-check-if-list-sorted)
|
||||||
|
@ -18,6 +18,18 @@
|
|||||||
<version>${org.assertj.core.version}</version>
|
<version>${org.assertj.core.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.commons</groupId>
|
||||||
|
<artifactId>commons-collections4</artifactId>
|
||||||
|
<version>${commons-collections4.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.google.guava</groupId>
|
||||||
|
<artifactId>guava</artifactId>
|
||||||
|
<version>${guava.version}</version>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
@ -34,6 +46,7 @@
|
|||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<org.assertj.core.version>3.9.0</org.assertj.core.version>
|
<org.assertj.core.version>3.9.0</org.assertj.core.version>
|
||||||
|
<commons-collections4.version>4.3</commons-collections4.version>
|
||||||
|
<guava.version>28.0-jre</guava.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -0,0 +1,34 @@
|
|||||||
|
package com.baeldung.algorithms.checksortedlist;
|
||||||
|
|
||||||
|
public class Employee {
|
||||||
|
|
||||||
|
long id;
|
||||||
|
|
||||||
|
String name;
|
||||||
|
|
||||||
|
public Employee() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public Employee(long id, String name) {
|
||||||
|
super();
|
||||||
|
this.id = id;
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setId(long id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,87 @@
|
|||||||
|
package com.baeldung.algorithms.checksortedlist;
|
||||||
|
|
||||||
|
import static org.apache.commons.collections4.CollectionUtils.isEmpty;
|
||||||
|
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.Iterator;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import com.google.common.collect.Comparators;
|
||||||
|
import com.google.common.collect.Ordering;;
|
||||||
|
|
||||||
|
public class SortedListChecker {
|
||||||
|
|
||||||
|
private SortedListChecker() {
|
||||||
|
throw new AssertionError();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean checkIfSortedUsingIterativeApproach(List<String> listOfStrings) {
|
||||||
|
if (isEmpty(listOfStrings) || listOfStrings.size() == 1) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
Iterator<String> iter = listOfStrings.iterator();
|
||||||
|
String current, previous = iter.next();
|
||||||
|
while (iter.hasNext()) {
|
||||||
|
current = iter.next();
|
||||||
|
if (previous.compareTo(current) > 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
previous = current;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean checkIfSortedUsingIterativeApproach(List<Employee> employees, Comparator<Employee> employeeComparator) {
|
||||||
|
if (isEmpty(employees) || employees.size() == 1) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
Iterator<Employee> iter = employees.iterator();
|
||||||
|
Employee current, previous = iter.next();
|
||||||
|
while (iter.hasNext()) {
|
||||||
|
current = iter.next();
|
||||||
|
if (employeeComparator.compare(previous, current) > 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
previous = current;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean checkIfSortedUsingRecursion(List<String> listOfStrings) {
|
||||||
|
return isSortedRecursive(listOfStrings, listOfStrings.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean isSortedRecursive(List<String> listOfStrings, int index) {
|
||||||
|
if (index < 2) {
|
||||||
|
return true;
|
||||||
|
} else if (listOfStrings.get(index - 2)
|
||||||
|
.compareTo(listOfStrings.get(index - 1)) > 0) {
|
||||||
|
return false;
|
||||||
|
} else {
|
||||||
|
return isSortedRecursive(listOfStrings, index - 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean checkIfSortedUsingOrderingClass(List<String> listOfStrings) {
|
||||||
|
return Ordering.<String> natural()
|
||||||
|
.isOrdered(listOfStrings);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean checkIfSortedUsingOrderingClass(List<Employee> employees, Comparator<Employee> employeeComparator) {
|
||||||
|
return Ordering.from(employeeComparator)
|
||||||
|
.isOrdered(employees);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean checkIfSortedUsingOrderingClassHandlingNull(List<String> listOfStrings) {
|
||||||
|
return Ordering.<String> natural()
|
||||||
|
.nullsLast()
|
||||||
|
.isOrdered(listOfStrings);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean checkIfSortedUsingComparators(List<String> listOfStrings) {
|
||||||
|
return Comparators.isInOrder(listOfStrings, Comparator.<String> naturalOrder());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,78 @@
|
|||||||
|
package com.baeldung.folding;
|
||||||
|
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.IntStream;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calculate a hash value for the strings using the folding technique.
|
||||||
|
*
|
||||||
|
* The implementation serves only to the illustration purposes and is far
|
||||||
|
* from being the most efficient.
|
||||||
|
*
|
||||||
|
* @author A.Shcherbakov
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
public class FoldingHash {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calculate the hash value of a given string.
|
||||||
|
*
|
||||||
|
* @param str Assume it is not null
|
||||||
|
* @param groupSize the group size in the folding technique
|
||||||
|
* @param maxValue defines a max value that the hash may acquire (exclusive)
|
||||||
|
* @return integer value from 0 (inclusive) to maxValue (exclusive)
|
||||||
|
*/
|
||||||
|
public int hash(String str, int groupSize, int maxValue) {
|
||||||
|
final int[] codes = this.toAsciiCodes(str);
|
||||||
|
return IntStream.range(0, str.length())
|
||||||
|
.filter(i -> i % groupSize == 0)
|
||||||
|
.mapToObj(i -> extract(codes, i, groupSize))
|
||||||
|
.map(block -> concatenate(block))
|
||||||
|
.reduce(0, (a, b) -> (a + b) % maxValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns a new array of given length whose elements are take from
|
||||||
|
* the original one starting from the offset.
|
||||||
|
*
|
||||||
|
* If the original array has not enough elements, the returning array will contain
|
||||||
|
* element from the offset till the end of the original array.
|
||||||
|
*
|
||||||
|
* @param numbers original array. Assume it is not null.
|
||||||
|
* @param offset index of the element to start from. Assume it is less than the size of the array
|
||||||
|
* @param length max size of the resulting array
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public int[] extract(int[] numbers, int offset, int length) {
|
||||||
|
final int defect = numbers.length - (offset + length);
|
||||||
|
final int s = defect < 0 ? length + defect : length;
|
||||||
|
int[] result = new int[s];
|
||||||
|
for (int index = 0; index < s; index++) {
|
||||||
|
result[index] = numbers[index + offset];
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Concatenate the numbers into a single number as if they were strings.
|
||||||
|
* Assume that the procedure does not suffer from the overflow.
|
||||||
|
* @param numbers integers to concatenate
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public int concatenate(int[] numbers) {
|
||||||
|
final String merged = IntStream.of(numbers)
|
||||||
|
.mapToObj(number -> "" + number)
|
||||||
|
.collect(Collectors.joining());
|
||||||
|
return Integer.parseInt(merged, 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert the string into its characters' ASCII codes.
|
||||||
|
* @param str input string
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
private int[] toAsciiCodes(String str) {
|
||||||
|
return str.chars()
|
||||||
|
.toArray();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,17 @@
|
|||||||
|
package com.baeldung.folding;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Code snippet for article "A Guide to the Folding Technique".
|
||||||
|
*
|
||||||
|
* @author A.Shcherbakov
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
public class Main {
|
||||||
|
|
||||||
|
public static void main(String... arg) {
|
||||||
|
FoldingHash hasher = new FoldingHash();
|
||||||
|
final String str = "Java language";
|
||||||
|
System.out.println(hasher.hash(str, 2, 100_000));
|
||||||
|
System.out.println(hasher.hash(str, 3, 1_000));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,106 @@
|
|||||||
|
package com.baeldung.algorithms.checksortedlist;
|
||||||
|
|
||||||
|
import static com.baeldung.algorithms.checksortedlist.SortedListChecker.checkIfSortedUsingComparators;
|
||||||
|
import static com.baeldung.algorithms.checksortedlist.SortedListChecker.checkIfSortedUsingIterativeApproach;
|
||||||
|
import static com.baeldung.algorithms.checksortedlist.SortedListChecker.checkIfSortedUsingOrderingClass;
|
||||||
|
import static com.baeldung.algorithms.checksortedlist.SortedListChecker.checkIfSortedUsingRecursion;
|
||||||
|
import static java.util.Arrays.asList;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class SortedListCheckerUnitTest {
|
||||||
|
|
||||||
|
private List<String> sortedListOfString;
|
||||||
|
private List<String> unsortedListOfString;
|
||||||
|
private List<String> singletonList;
|
||||||
|
|
||||||
|
private List<Employee> employeesSortedByName;
|
||||||
|
private List<Employee> employeesNotSortedByName;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setUp() {
|
||||||
|
sortedListOfString = asList("Canada", "HK", "LA", "NJ", "NY");
|
||||||
|
unsortedListOfString = asList("LA", "HK", "NJ", "NY", "Canada");
|
||||||
|
singletonList = Collections.singletonList("NY");
|
||||||
|
|
||||||
|
employeesSortedByName = asList(new Employee(1L, "John"), new Employee(2L, "Kevin"), new Employee(3L, "Mike"));
|
||||||
|
employeesNotSortedByName = asList(new Employee(1L, "Kevin"), new Employee(2L, "John"), new Employee(3L, "Mike"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSortedList_whenUsingIterativeApproach_thenReturnTrue() {
|
||||||
|
assertThat(checkIfSortedUsingIterativeApproach(sortedListOfString)).isTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSingleElementList_whenUsingIterativeApproach_thenReturnTrue() {
|
||||||
|
assertThat(checkIfSortedUsingIterativeApproach(singletonList)).isTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUnsortedList_whenUsingIterativeApproach_thenReturnFalse() {
|
||||||
|
assertThat(checkIfSortedUsingIterativeApproach(unsortedListOfString)).isFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSortedListOfEmployees_whenUsingIterativeApproach_thenReturnTrue() {
|
||||||
|
assertThat(checkIfSortedUsingIterativeApproach(employeesSortedByName, Comparator.comparing(Employee::getName))).isTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUnsortedListOfEmployees_whenUsingIterativeApproach_thenReturnFalse() {
|
||||||
|
assertThat(checkIfSortedUsingIterativeApproach(employeesNotSortedByName, Comparator.comparing(Employee::getName))).isFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSortedList_whenUsingRecursion_thenReturnTrue() {
|
||||||
|
assertThat(checkIfSortedUsingRecursion(sortedListOfString)).isTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSingleElementList_whenUsingRecursion_thenReturnTrue() {
|
||||||
|
assertThat(checkIfSortedUsingRecursion(singletonList)).isTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUnsortedList_whenUsingRecursion_thenReturnFalse() {
|
||||||
|
assertThat(checkIfSortedUsingRecursion(unsortedListOfString)).isFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSortedList_whenUsingGuavaOrdering_thenReturnTrue() {
|
||||||
|
assertThat(checkIfSortedUsingOrderingClass(sortedListOfString)).isTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUnsortedList_whenUsingGuavaOrdering_thenReturnFalse() {
|
||||||
|
assertThat(checkIfSortedUsingOrderingClass(unsortedListOfString)).isFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSortedListOfEmployees_whenUsingGuavaOrdering_thenReturnTrue() {
|
||||||
|
assertThat(checkIfSortedUsingOrderingClass(employeesSortedByName, Comparator.comparing(Employee::getName))).isTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUnsortedListOfEmployees_whenUsingGuavaOrdering_thenReturnFalse() {
|
||||||
|
assertThat(checkIfSortedUsingOrderingClass(employeesNotSortedByName, Comparator.comparing(Employee::getName))).isFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSortedList_whenUsingGuavaComparators_thenReturnTrue() {
|
||||||
|
assertThat(checkIfSortedUsingComparators(sortedListOfString)).isTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUnsortedList_whenUsingGuavaComparators_thenReturnFalse() {
|
||||||
|
assertThat(checkIfSortedUsingComparators(unsortedListOfString)).isFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,54 @@
|
|||||||
|
package com.baeldung.folding;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertArrayEquals;
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class FoldingHashUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenStringJavaLanguage_whenSize2Capacity100000_then48933() throws Exception {
|
||||||
|
final FoldingHash hasher = new FoldingHash();
|
||||||
|
final int value = hasher.hash("Java language", 2, 100_000);
|
||||||
|
assertEquals(value, 48933);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenStringVaJaLanguage_whenSize2Capacity100000_thenSameAsJavaLanguage() throws Exception {
|
||||||
|
final FoldingHash hasher = new FoldingHash();
|
||||||
|
final int java = hasher.hash("Java language", 2, 100_000);
|
||||||
|
final int vaja = hasher.hash("vaJa language", 2, 100_000);
|
||||||
|
assertTrue(java == vaja);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSingleElementArray_whenOffset0Size2_thenSingleElement() throws Exception {
|
||||||
|
final FoldingHash hasher = new FoldingHash();
|
||||||
|
final int[] value = hasher.extract(new int[] { 5 }, 0, 2);
|
||||||
|
assertArrayEquals(new int[] { 5 }, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenFiveElementArray_whenOffset0Size3_thenFirstThreeElements() throws Exception {
|
||||||
|
final FoldingHash hasher = new FoldingHash();
|
||||||
|
final int[] value = hasher.extract(new int[] { 1, 2, 3, 4, 5 }, 0, 3);
|
||||||
|
assertArrayEquals(new int[] { 1, 2, 3 }, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenFiveElementArray_whenOffset1Size2_thenTwoElements() throws Exception {
|
||||||
|
final FoldingHash hasher = new FoldingHash();
|
||||||
|
final int[] value = hasher.extract(new int[] { 1, 2, 3, 4, 5 }, 1, 2);
|
||||||
|
assertArrayEquals(new int[] { 2, 3 }, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenFiveElementArray_whenOffset2SizeTooBig_thenElementsToTheEnd() throws Exception {
|
||||||
|
final FoldingHash hasher = new FoldingHash();
|
||||||
|
final int[] value = hasher.extract(new int[] { 1, 2, 3, 4, 5 }, 2, 2000);
|
||||||
|
assertArrayEquals(new int[] { 3, 4, 5 }, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -29,6 +29,12 @@
|
|||||||
</exclusion>
|
</exclusion>
|
||||||
</exclusions>
|
</exclusions>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.google.auto.service</groupId>
|
||||||
|
<artifactId>auto-service</artifactId>
|
||||||
|
<version>${auto-service.version}</version>
|
||||||
|
<optional>true</optional>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.google.inject</groupId>
|
<groupId>com.google.inject</groupId>
|
||||||
@ -40,6 +46,7 @@
|
|||||||
<properties>
|
<properties>
|
||||||
<auto-value.version>1.3</auto-value.version>
|
<auto-value.version>1.3</auto-value.version>
|
||||||
<auto-factory.version>1.0-beta5</auto-factory.version>
|
<auto-factory.version>1.0-beta5</auto-factory.version>
|
||||||
|
<auto-service.version>1.0-rc5</auto-service.version>
|
||||||
<guice.version>4.2.0</guice.version>
|
<guice.version>4.2.0</guice.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
|
@ -0,0 +1,14 @@
|
|||||||
|
package com.baeldung.autoservice;
|
||||||
|
|
||||||
|
import com.google.auto.service.AutoService;
|
||||||
|
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
|
@AutoService(TranslationService.class)
|
||||||
|
public class BingTranslationServiceProvider implements TranslationService {
|
||||||
|
@Override
|
||||||
|
public String translate(String message, Locale from, Locale to) {
|
||||||
|
// implementation details
|
||||||
|
return message + " (translated by Bing)";
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,14 @@
|
|||||||
|
package com.baeldung.autoservice;
|
||||||
|
|
||||||
|
import com.google.auto.service.AutoService;
|
||||||
|
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
|
@AutoService(TranslationService.class)
|
||||||
|
public class GoogleTranslationServiceProvider implements TranslationService {
|
||||||
|
@Override
|
||||||
|
public String translate(String message, Locale from, Locale to) {
|
||||||
|
// implementation details
|
||||||
|
return message + " (translated by Google)";
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,7 @@
|
|||||||
|
package com.baeldung.autoservice;
|
||||||
|
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
|
public interface TranslationService {
|
||||||
|
String translate(String message, Locale from, Locale to);
|
||||||
|
}
|
@ -0,0 +1,37 @@
|
|||||||
|
package com.baeldung.autoservice;
|
||||||
|
|
||||||
|
import com.baeldung.autoservice.TranslationService;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.ServiceLoader;
|
||||||
|
import java.util.stream.StreamSupport;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
public class TranslationServiceUnitTest {
|
||||||
|
|
||||||
|
private ServiceLoader<TranslationService> loader;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setUp() {
|
||||||
|
loader = ServiceLoader.load(TranslationService.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenServiceLoaderLoads_thenLoadsAllProviders() {
|
||||||
|
long count = StreamSupport.stream(loader.spliterator(), false).count();
|
||||||
|
assertEquals(2, count);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenServiceLoaderLoadsGoogleService_thenGoogleIsLoaded() {
|
||||||
|
TranslationService googleService = StreamSupport.stream(loader.spliterator(), false)
|
||||||
|
.filter(p -> p.getClass().getSimpleName().equals("GoogleTranslationServiceProvider"))
|
||||||
|
.findFirst()
|
||||||
|
.get();
|
||||||
|
|
||||||
|
String message = "message";
|
||||||
|
assertEquals(message + " (translated by Google)", googleService.translate(message, null, null));
|
||||||
|
}
|
||||||
|
}
|
@ -6,3 +6,4 @@
|
|||||||
- [Template Engines in Groovy](https://www.baeldung.com/groovy-template-engines)
|
- [Template Engines in Groovy](https://www.baeldung.com/groovy-template-engines)
|
||||||
- [Groovy def Keyword](https://www.baeldung.com/groovy-def-keyword)
|
- [Groovy def Keyword](https://www.baeldung.com/groovy-def-keyword)
|
||||||
- [Pattern Matching in Strings in Groovy](https://www.baeldung.com/groovy-pattern-matching)
|
- [Pattern Matching in Strings in Groovy](https://www.baeldung.com/groovy-pattern-matching)
|
||||||
|
- [Working with XML in Groovy](https://www.baeldung.com/groovy-xml)
|
@ -22,6 +22,7 @@
|
|||||||
<maven.compiler.source>1.8</maven.compiler.source>
|
<maven.compiler.source>1.8</maven.compiler.source>
|
||||||
<maven.compiler.target>1.8</maven.compiler.target>
|
<maven.compiler.target>1.8</maven.compiler.target>
|
||||||
<icu.version>64.2</icu.version>
|
<icu.version>64.2</icu.version>
|
||||||
|
<assertj.version>3.12.2</assertj.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
@ -30,6 +31,12 @@
|
|||||||
<artifactId>icu4j</artifactId>
|
<artifactId>icu4j</artifactId>
|
||||||
<version>${icu.version}</version>
|
<version>${icu.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.assertj</groupId>
|
||||||
|
<artifactId>assertj-core</artifactId>
|
||||||
|
<version>${assertj.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
|
@ -0,0 +1,84 @@
|
|||||||
|
package com.baeldung.forEach;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Iterator;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
|
class ReverseList extends ArrayList<String> {
|
||||||
|
|
||||||
|
List<String> list = Arrays.asList("A", "B", "C", "D");
|
||||||
|
|
||||||
|
Consumer<String> removeElement = s -> {
|
||||||
|
System.out.println(s + " " + list.size());
|
||||||
|
if (s != null && s.equals("A")) {
|
||||||
|
list.remove("D");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Iterator<String> iterator() {
|
||||||
|
|
||||||
|
final int startIndex = this.size() - 1;
|
||||||
|
final List<String> list = this;
|
||||||
|
return new Iterator<String>() {
|
||||||
|
|
||||||
|
int currentIndex = startIndex;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean hasNext() {
|
||||||
|
return currentIndex >= 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String next() {
|
||||||
|
String next = list.get(currentIndex);
|
||||||
|
currentIndex--;
|
||||||
|
return next;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void remove() {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public void forEach(Consumer<? super String> action) {
|
||||||
|
for (String s : this) {
|
||||||
|
action.accept(s);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void iterateParallel() {
|
||||||
|
list.forEach(System.out::print);
|
||||||
|
System.out.print(" ");
|
||||||
|
list.parallelStream().forEach(System.out::print);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void iterateReverse() {
|
||||||
|
List<String> myList = new ReverseList();
|
||||||
|
myList.addAll(list);
|
||||||
|
myList.forEach(System.out::print);
|
||||||
|
System.out.print(" ");
|
||||||
|
myList.stream().forEach(System.out::print);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void removeInCollectionForEach() {
|
||||||
|
list.forEach(removeElement);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void removeInStreamForEach() {
|
||||||
|
list.stream().forEach(removeElement);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] argv) {
|
||||||
|
|
||||||
|
ReverseList collectionForEach = new ReverseList();
|
||||||
|
collectionForEach.iterateParallel();
|
||||||
|
collectionForEach.iterateReverse();
|
||||||
|
collectionForEach.removeInCollectionForEach();
|
||||||
|
collectionForEach.removeInStreamForEach();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,46 @@
|
|||||||
|
package com.baeldung.stream;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
public class SkipLimitComparison {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
skipExample();
|
||||||
|
limitExample();
|
||||||
|
limitInfiniteStreamExample();
|
||||||
|
getEvenNumbers(10, 10).stream()
|
||||||
|
.forEach(System.out::println);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void skipExample() {
|
||||||
|
Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
|
||||||
|
.filter(i -> i % 2 == 0)
|
||||||
|
.skip(2)
|
||||||
|
.forEach(i -> System.out.print(i + " "));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void limitExample() {
|
||||||
|
Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
|
||||||
|
.filter(i -> i % 2 == 0)
|
||||||
|
.limit(2)
|
||||||
|
.forEach(i -> System.out.print(i + " "));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void limitInfiniteStreamExample() {
|
||||||
|
Stream.iterate(0, i -> i + 1)
|
||||||
|
.filter(i -> i % 2 == 0)
|
||||||
|
.limit(10)
|
||||||
|
.forEach(System.out::println);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<Integer> getEvenNumbers(int offset, int limit) {
|
||||||
|
return Stream.iterate(0, i -> i + 1)
|
||||||
|
.filter(i -> i % 2 == 0)
|
||||||
|
.skip(offset)
|
||||||
|
.limit(limit)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,164 @@
|
|||||||
|
package com.baeldung.bifunction;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.function.BiFunction;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
public class BiFunctionalInterfacesUnitTest {
|
||||||
|
@Test
|
||||||
|
public void givenStreamValues_whenMappedToNewValues() {
|
||||||
|
List<String> mapped = Stream.of("hello", "world")
|
||||||
|
.map(word -> word + "!")
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
|
assertThat(mapped).containsExactly("hello!", "world!");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenStreamValues_whenReducedWithPrefixingOperation() {
|
||||||
|
String result = Stream.of("hello", "world")
|
||||||
|
.reduce("", (a, b) -> b + "-" + a);
|
||||||
|
|
||||||
|
assertThat(result).isEqualTo("world-hello-");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenStreamValues_whenReducedWithPrefixingLambda_thenHasNoTrailingDash() {
|
||||||
|
String result = Stream.of("hello", "world")
|
||||||
|
.reduce("", (a, b) -> combineWithoutTrailingDash(a, b));
|
||||||
|
|
||||||
|
assertThat(result).isEqualTo("world-hello");
|
||||||
|
}
|
||||||
|
|
||||||
|
private String combineWithoutTrailingDash(String a, String b) {
|
||||||
|
if (a.isEmpty()) {
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
return b + "-" + a;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenStreamValues_whenReducedWithPrefixingMethodReference_thenHasNoTrailingDash() {
|
||||||
|
String result = Stream.of("hello", "world")
|
||||||
|
.reduce("", this::combineWithoutTrailingDash);
|
||||||
|
|
||||||
|
assertThat(result).isEqualTo("world-hello");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoLists_whenCombined() {
|
||||||
|
List<String> list1 = Arrays.asList("a", "b", "c");
|
||||||
|
List<Integer> list2 = Arrays.asList(1, 2, 3);
|
||||||
|
|
||||||
|
List<String> result = new ArrayList<>();
|
||||||
|
for (int i=0; i < list1.size(); i++) {
|
||||||
|
result.add(list1.get(i) + list2.get(i));
|
||||||
|
}
|
||||||
|
|
||||||
|
assertThat(result).containsExactly("a1", "b2", "c3");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoLists_whenCombinedWithGeneralPurposeCombiner() {
|
||||||
|
List<String> list1 = Arrays.asList("a", "b", "c");
|
||||||
|
List<Integer> list2 = Arrays.asList(1, 2, 3);
|
||||||
|
|
||||||
|
List<String> result = listCombiner(list1, list2, (a, b) -> a + b);
|
||||||
|
|
||||||
|
assertThat(result).containsExactly("a1", "b2", "c3");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static <T, U, R> List<R> listCombiner(List<T> list1,
|
||||||
|
List<U> list2,
|
||||||
|
BiFunction<T, U, R> combiner) {
|
||||||
|
List<R> result = new ArrayList<>();
|
||||||
|
for (int i = 0; i < list1.size(); i++) {
|
||||||
|
result.add(combiner.apply(list1.get(i), list2.get(i)));
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoLists_whenComparedWithCombiningFunction() {
|
||||||
|
List<Double> list1 = Arrays.asList(1.0d, 2.1d, 3.3d);
|
||||||
|
List<Float> list2 = Arrays.asList(0.1f, 0.2f, 4f);
|
||||||
|
|
||||||
|
// algorithm to determine if the value in list1 > value in list 2
|
||||||
|
List<Boolean> result = listCombiner(list1, list2, (a, b) -> a > b);
|
||||||
|
|
||||||
|
assertThat(result).containsExactly(true, true, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoLists_whenComparedWithCombiningFunctionByMethodReference() {
|
||||||
|
List<Double> list1 = Arrays.asList(1.0d, 2.1d, 3.3d);
|
||||||
|
List<Float> list2 = Arrays.asList(0.1f, 0.2f, 4f);
|
||||||
|
|
||||||
|
// algorithm to determine if the value in list1 > value in list 2
|
||||||
|
List<Boolean> result = listCombiner(list1, list2, this::firstIsGreaterThanSecond);
|
||||||
|
|
||||||
|
assertThat(result).containsExactly(true, true, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean firstIsGreaterThanSecond(Double a, Float b) {
|
||||||
|
return a > b;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoLists_whenComparedForEqualityByCombiningFunction() {
|
||||||
|
List<Float> list1 = Arrays.asList(0.1f, 0.2f, 4f);
|
||||||
|
List<Float> list2 = Arrays.asList(0.1f, 0.2f, 4f);
|
||||||
|
|
||||||
|
List<Boolean> result = listCombiner(list1, list2, (a, b) -> a.equals(b));
|
||||||
|
|
||||||
|
assertThat(result).containsExactly(true, true, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoLists_whenComparedForEqualityByCombiningFunctionWithMethodReference() {
|
||||||
|
List<Float> list1 = Arrays.asList(0.1f, 0.2f, 4f);
|
||||||
|
List<Float> list2 = Arrays.asList(0.1f, 0.2f, 4f);
|
||||||
|
|
||||||
|
List<Boolean> result = listCombiner(list1, list2, Float::equals);
|
||||||
|
|
||||||
|
assertThat(result).containsExactly(true, true, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoLists_whenComparedWithCombiningFunctionWithCompareTo() {
|
||||||
|
List<Double> list1 = Arrays.asList(1.0d, 2.1d, 3.3d);
|
||||||
|
List<Double> list2 = Arrays.asList(0.1d, 0.2d, 4d);
|
||||||
|
|
||||||
|
List<Integer> result = listCombiner(list1, list2, Double::compareTo);
|
||||||
|
|
||||||
|
assertThat(result).containsExactly(1, 1, -1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Allows you to to pass in a lambda or method reference and then
|
||||||
|
* get access to the BiFunction it is meant to become
|
||||||
|
*/
|
||||||
|
private static <T, U, R> BiFunction<T, U, R> asBiFunction(BiFunction<T, U, R> function) {
|
||||||
|
return function;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoLists_whenComparedWithCombiningFunctionWithComposedBiFunction() {
|
||||||
|
List<Double> list1 = Arrays.asList(1.0d, 2.1d, 3.3d);
|
||||||
|
List<Double> list2 = Arrays.asList(0.1d, 0.2d, 4d);
|
||||||
|
|
||||||
|
List<Boolean> result = listCombiner(list1, list2,
|
||||||
|
asBiFunction(Double::compareTo)
|
||||||
|
.andThen(i -> i > 0));
|
||||||
|
|
||||||
|
assertThat(result).containsExactly(true, true, false);
|
||||||
|
}
|
||||||
|
}
|
@ -389,7 +389,7 @@
|
|||||||
<properties>
|
<properties>
|
||||||
|
|
||||||
<!-- util -->
|
<!-- util -->
|
||||||
<commons-lang3.version>3.8.1</commons-lang3.version>
|
<commons-lang3.version>3.9</commons-lang3.version>
|
||||||
|
|
||||||
<jmh-core.version>1.19</jmh-core.version>
|
<jmh-core.version>1.19</jmh-core.version>
|
||||||
<jmh-generator-annprocess.version>1.19</jmh-generator-annprocess.version>
|
<jmh-generator-annprocess.version>1.19</jmh-generator-annprocess.version>
|
||||||
|
@ -1,49 +0,0 @@
|
|||||||
package com.baeldung.array;
|
|
||||||
|
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.Scanner;
|
|
||||||
|
|
||||||
public class JaggedArray {
|
|
||||||
|
|
||||||
int[][] shortHandFormInitialization() {
|
|
||||||
int[][] jaggedArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } };
|
|
||||||
return jaggedArr;
|
|
||||||
}
|
|
||||||
|
|
||||||
int[][] declarationAndThenInitialization() {
|
|
||||||
int[][] jaggedArr = new int[3][];
|
|
||||||
jaggedArr[0] = new int[] { 1, 2 };
|
|
||||||
jaggedArr[1] = new int[] { 3, 4, 5 };
|
|
||||||
jaggedArr[2] = new int[] { 6, 7, 8, 9 };
|
|
||||||
return jaggedArr;
|
|
||||||
}
|
|
||||||
|
|
||||||
int[][] declarationAndThenInitializationUsingUserInputs() {
|
|
||||||
int[][] jaggedArr = new int[3][];
|
|
||||||
jaggedArr[0] = new int[2];
|
|
||||||
jaggedArr[1] = new int[3];
|
|
||||||
jaggedArr[2] = new int[4];
|
|
||||||
initializeElements(jaggedArr);
|
|
||||||
return jaggedArr;
|
|
||||||
}
|
|
||||||
|
|
||||||
void initializeElements(int[][] jaggedArr) {
|
|
||||||
Scanner sc = new Scanner(System.in);
|
|
||||||
for (int outer = 0; outer < jaggedArr.length; outer++) {
|
|
||||||
for (int inner = 0; inner < jaggedArr[outer].length; inner++) {
|
|
||||||
jaggedArr[outer][inner] = sc.nextInt();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void printElements(int[][] jaggedArr) {
|
|
||||||
for (int index = 0; index < jaggedArr.length; index++) {
|
|
||||||
System.out.println(Arrays.toString(jaggedArr[index]));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
int[] getElementAtGivenIndex(int[][] jaggedArr, int index) {
|
|
||||||
return jaggedArr[index];
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -0,0 +1,83 @@
|
|||||||
|
package com.baeldung.array;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Scanner;
|
||||||
|
|
||||||
|
public class MultiDimensionalArray {
|
||||||
|
|
||||||
|
int[][] shortHandFormInitialization() {
|
||||||
|
int[][] multiDimensionalArray = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } };
|
||||||
|
return multiDimensionalArray;
|
||||||
|
}
|
||||||
|
|
||||||
|
int[][] declarationAndThenInitialization() {
|
||||||
|
int[][] multiDimensionalArray = new int[3][];
|
||||||
|
multiDimensionalArray[0] = new int[] { 1, 2 };
|
||||||
|
multiDimensionalArray[1] = new int[] { 3, 4, 5 };
|
||||||
|
multiDimensionalArray[2] = new int[] { 6, 7, 8, 9 };
|
||||||
|
return multiDimensionalArray;
|
||||||
|
}
|
||||||
|
|
||||||
|
int[][] declarationAndThenInitializationUsingUserInputs() {
|
||||||
|
int[][] multiDimensionalArray = new int[3][];
|
||||||
|
multiDimensionalArray[0] = new int[2];
|
||||||
|
multiDimensionalArray[1] = new int[3];
|
||||||
|
multiDimensionalArray[2] = new int[4];
|
||||||
|
initializeElements(multiDimensionalArray);
|
||||||
|
return multiDimensionalArray;
|
||||||
|
}
|
||||||
|
|
||||||
|
void initializeElements(int[][] multiDimensionalArray) {
|
||||||
|
Scanner sc = new Scanner(System.in);
|
||||||
|
for (int outer = 0; outer < multiDimensionalArray.length; outer++) {
|
||||||
|
for (int inner = 0; inner < multiDimensionalArray[outer].length; inner++) {
|
||||||
|
multiDimensionalArray[outer][inner] = sc.nextInt();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void initialize2DArray(int[][] multiDimensionalArray) {
|
||||||
|
for (int[] array : multiDimensionalArray) {
|
||||||
|
Arrays.fill(array, 7);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void printElements(int[][] multiDimensionalArray) {
|
||||||
|
for (int index = 0; index < multiDimensionalArray.length; index++) {
|
||||||
|
System.out.println(Arrays.toString(multiDimensionalArray[index]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int[] getElementAtGivenIndex(int[][] multiDimensionalArray, int index) {
|
||||||
|
return multiDimensionalArray[index];
|
||||||
|
}
|
||||||
|
|
||||||
|
int[] findLengthOfElements(int[][] multiDimensionalArray) {
|
||||||
|
int[] arrayOfLengths = new int[multiDimensionalArray.length];
|
||||||
|
for (int i = 0; i < multiDimensionalArray.length; i++) {
|
||||||
|
arrayOfLengths[i] = multiDimensionalArray[i].length;
|
||||||
|
}
|
||||||
|
return arrayOfLengths;
|
||||||
|
}
|
||||||
|
|
||||||
|
Integer[] findLengthOfElements(Integer[][] multiDimensionalArray) {
|
||||||
|
return Arrays.stream(multiDimensionalArray)
|
||||||
|
.map(array -> array.length)
|
||||||
|
.toArray(Integer[]::new);
|
||||||
|
}
|
||||||
|
|
||||||
|
int[][] copy2DArray(int[][] arrayOfArrays) {
|
||||||
|
int[][] copied2DArray = new int[arrayOfArrays.length][];
|
||||||
|
for (int i = 0; i < arrayOfArrays.length; i++) {
|
||||||
|
int[] array = arrayOfArrays[i];
|
||||||
|
copied2DArray[i] = Arrays.copyOf(array, array.length);
|
||||||
|
}
|
||||||
|
return copied2DArray;
|
||||||
|
}
|
||||||
|
|
||||||
|
Integer[][] copy2DArray(Integer[][] arrayOfArrays) {
|
||||||
|
return Arrays.stream(arrayOfArrays)
|
||||||
|
.map(array -> Arrays.copyOf(array, array.length))
|
||||||
|
.toArray(Integer[][]::new);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,27 @@
|
|||||||
|
package com.baeldung.array;
|
||||||
|
|
||||||
|
import org.apache.commons.lang3.ArrayUtils;
|
||||||
|
|
||||||
|
public class RemoveElementFromAnArray {
|
||||||
|
|
||||||
|
public int[] removeAnElementWithAGivenIndex(int[] array, int index) {
|
||||||
|
return ArrayUtils.remove(array, index);
|
||||||
|
}
|
||||||
|
|
||||||
|
public int[] removeAllElementsWithGivenIndices(int[] array, int... indicies) {
|
||||||
|
return ArrayUtils.removeAll(array, indicies);
|
||||||
|
}
|
||||||
|
|
||||||
|
public int[] removeFirstOccurrenceOfGivenElement(int[] array, int element) {
|
||||||
|
return ArrayUtils.removeElement(array, element);
|
||||||
|
}
|
||||||
|
|
||||||
|
public int[] removeAllGivenElements(int[] array, int... elements) {
|
||||||
|
return ArrayUtils.removeElements(array, elements);
|
||||||
|
}
|
||||||
|
|
||||||
|
public int[] removeAllOccurrencesOfAGivenElement(int[] array, int element) {
|
||||||
|
return ArrayUtils.removeAllOccurences(array, element);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -1,53 +0,0 @@
|
|||||||
package com.baeldung.array;
|
|
||||||
|
|
||||||
import static org.junit.Assert.assertArrayEquals;
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
|
|
||||||
import java.io.ByteArrayInputStream;
|
|
||||||
import java.io.ByteArrayOutputStream;
|
|
||||||
import java.io.InputStream;
|
|
||||||
import java.io.PrintStream;
|
|
||||||
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
public class JaggedArrayUnitTest {
|
|
||||||
|
|
||||||
private JaggedArray obj = new JaggedArray();
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenInitializedUsingShortHandForm_thenCorrect() {
|
|
||||||
assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.shortHandFormInitialization());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenInitializedWithDeclarationAndThenInitalization_thenCorrect() {
|
|
||||||
assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.declarationAndThenInitialization());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenInitializedWithDeclarationAndThenInitalizationUsingUserInputs_thenCorrect() {
|
|
||||||
InputStream is = new ByteArrayInputStream("1 2 3 4 5 6 7 8 9".getBytes());
|
|
||||||
System.setIn(is);
|
|
||||||
assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.declarationAndThenInitializationUsingUserInputs());
|
|
||||||
System.setIn(System.in);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenJaggedArrayAndAnIndex_thenReturnArrayAtGivenIndex() {
|
|
||||||
int[][] jaggedArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } };
|
|
||||||
assertArrayEquals(new int[] { 1, 2 }, obj.getElementAtGivenIndex(jaggedArr, 0));
|
|
||||||
assertArrayEquals(new int[] { 3, 4, 5 }, obj.getElementAtGivenIndex(jaggedArr, 1));
|
|
||||||
assertArrayEquals(new int[] { 6, 7, 8, 9 }, obj.getElementAtGivenIndex(jaggedArr, 2));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenJaggedArray_whenUsingArraysAPI_thenVerifyPrintedElements() {
|
|
||||||
int[][] jaggedArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } };
|
|
||||||
ByteArrayOutputStream outContent = new ByteArrayOutputStream();
|
|
||||||
System.setOut(new PrintStream(outContent));
|
|
||||||
obj.printElements(jaggedArr);
|
|
||||||
assertEquals("[1, 2][3, 4, 5][6, 7, 8, 9]", outContent.toString().replace("\r", "").replace("\n", ""));
|
|
||||||
System.setOut(System.out);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -0,0 +1,86 @@
|
|||||||
|
package com.baeldung.array;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertArrayEquals;
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.io.PrintStream;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class MultiDimensionalArrayUnitTest {
|
||||||
|
|
||||||
|
private MultiDimensionalArray obj = new MultiDimensionalArray();
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenInitializedUsingShortHandForm_thenCorrect() {
|
||||||
|
assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.shortHandFormInitialization());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenInitializedWithDeclarationAndThenInitalization_thenCorrect() {
|
||||||
|
assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.declarationAndThenInitialization());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenInitializedWithDeclarationAndThenInitalizationUsingUserInputs_thenCorrect() {
|
||||||
|
InputStream is = new ByteArrayInputStream("1 2 3 4 5 6 7 8 9".getBytes());
|
||||||
|
System.setIn(is);
|
||||||
|
assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.declarationAndThenInitializationUsingUserInputs());
|
||||||
|
System.setIn(System.in);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMultiDimensionalArrayAndAnIndex_thenReturnArrayAtGivenIndex() {
|
||||||
|
int[][] multiDimensionalArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } };
|
||||||
|
assertArrayEquals(new int[] { 1, 2 }, obj.getElementAtGivenIndex(multiDimensionalArr, 0));
|
||||||
|
assertArrayEquals(new int[] { 3, 4, 5 }, obj.getElementAtGivenIndex(multiDimensionalArr, 1));
|
||||||
|
assertArrayEquals(new int[] { 6, 7, 8, 9 }, obj.getElementAtGivenIndex(multiDimensionalArr, 2));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMultiDimensionalArray_whenUsingArraysAPI_thenVerifyPrintedElements() {
|
||||||
|
int[][] multiDimensionalArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } };
|
||||||
|
ByteArrayOutputStream outContent = new ByteArrayOutputStream();
|
||||||
|
System.setOut(new PrintStream(outContent));
|
||||||
|
obj.printElements(multiDimensionalArr);
|
||||||
|
assertEquals("[1, 2][3, 4, 5][6, 7, 8, 9]", outContent.toString().replace("\r", "").replace("\n", ""));
|
||||||
|
System.setOut(System.out);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMultiDimensionalArray_whenUsingArraysFill_thenVerifyInitialize2DArray() {
|
||||||
|
int[][] multiDimensionalArr = new int[3][];
|
||||||
|
multiDimensionalArr[0] = new int[2];
|
||||||
|
multiDimensionalArr[1] = new int[3];
|
||||||
|
multiDimensionalArr[2] = new int[4];
|
||||||
|
obj.initialize2DArray(multiDimensionalArr);
|
||||||
|
assertArrayEquals(new int[][] {{7,7}, {7,7,7}, {7,7,7,7}}, multiDimensionalArr);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMultiDimensionalArray_whenUsingIteration_thenVerifyFindLengthOfElements() {
|
||||||
|
int[][] multiDimensionalArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } };
|
||||||
|
assertArrayEquals(new int[]{2,3,4}, obj.findLengthOfElements(multiDimensionalArr));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMultiDimensionalArray_whenUsingArraysStream_thenVerifyFindLengthOfElements() {
|
||||||
|
Integer[][] multiDimensionalArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } };
|
||||||
|
assertArrayEquals(new Integer[]{2,3,4}, obj.findLengthOfElements(multiDimensionalArr));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMultiDimensionalArray_whenUsingArraysCopyOf_thenVerifyCopy2DArray() {
|
||||||
|
int[][] multiDimensionalArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } };
|
||||||
|
assertArrayEquals(multiDimensionalArr, obj.copy2DArray(multiDimensionalArr));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMultiDimensionalArray_whenUsingArraysStream_thenVerifyCopy2DArray() {
|
||||||
|
Integer[][] multiDimensionalArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } };
|
||||||
|
assertArrayEquals(multiDimensionalArr, obj.copy2DArray(multiDimensionalArr));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,85 @@
|
|||||||
|
package com.baeldung.array;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
import org.apache.commons.lang3.ArrayUtils;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
class RemoveElementFromAnArrayUnitTest {
|
||||||
|
|
||||||
|
private final RemoveElementFromAnArray sut = new RemoveElementFromAnArray();
|
||||||
|
private final int[] inputArray = new int[] { 40, 10, 20, 30, 40, 50 };
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testRemoveAnElementWithAGivenIndex() {
|
||||||
|
int index = 2;
|
||||||
|
int[] modifiedArray = sut.removeAnElementWithAGivenIndex(inputArray, index);
|
||||||
|
|
||||||
|
assertFalse(ArrayUtils.contains(modifiedArray, inputArray[index]));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testRemoveAllElementsWithGivenIndices() {
|
||||||
|
int first = 0;
|
||||||
|
int last = inputArray.length - 1;
|
||||||
|
int[] modifiedArray = sut.removeAllElementsWithGivenIndices(inputArray, first, last);
|
||||||
|
|
||||||
|
assertFalse(ArrayUtils.contains(modifiedArray, inputArray[first]) && ArrayUtils.contains(modifiedArray, inputArray[last]));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testRemoveElement_WhenArrayIsNull_ThrowsIndexOutOfBoundEx() {
|
||||||
|
int index = 2;
|
||||||
|
|
||||||
|
assertThrows(IndexOutOfBoundsException.class, () -> {
|
||||||
|
sut.removeAnElementWithAGivenIndex(null, index);
|
||||||
|
});
|
||||||
|
|
||||||
|
assertThrows(IndexOutOfBoundsException.class, () -> {
|
||||||
|
sut.removeAllElementsWithGivenIndices(null, index);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testRemoveFirstOccurrenceOfGivenElement() {
|
||||||
|
int element = 40;
|
||||||
|
int[] modifiedArray = sut.removeFirstOccurrenceOfGivenElement(inputArray, element);
|
||||||
|
|
||||||
|
int indexInInputArray = ArrayUtils.indexOf(inputArray, element);
|
||||||
|
int indexInModifiedArray = ArrayUtils.indexOf(modifiedArray, element);
|
||||||
|
assertFalse(indexInInputArray == indexInModifiedArray);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testRemoveAllGivenElements() {
|
||||||
|
int duplicateElement = 40;
|
||||||
|
int[] elements = new int[] { duplicateElement, 10, 50 };
|
||||||
|
int[] modifiedArray = sut.removeAllGivenElements(inputArray, elements);
|
||||||
|
|
||||||
|
assertTrue(ArrayUtils.contains(modifiedArray, duplicateElement));
|
||||||
|
assertFalse(ArrayUtils.contains(modifiedArray, elements[1]));
|
||||||
|
assertFalse(ArrayUtils.contains(modifiedArray, elements[2]));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testRemoveAllOccurrencesOfAGivenElement() {
|
||||||
|
int element = 40;
|
||||||
|
int[] modifiedArray = sut.removeAllOccurrencesOfAGivenElement(inputArray, element);
|
||||||
|
|
||||||
|
assertFalse(ArrayUtils.contains(modifiedArray, element));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testRemoveElement_WhenArrayIsNull_ReturnsNull() {
|
||||||
|
int element = 20;
|
||||||
|
|
||||||
|
assertEquals(null, sut.removeFirstOccurrenceOfGivenElement(null, element));
|
||||||
|
assertEquals(null, sut.removeAllGivenElements(null, element));
|
||||||
|
assertEquals(null, sut.removeAllOccurrencesOfAGivenElement(null, element));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -14,6 +14,10 @@
|
|||||||
<relativePath>../../parent-java</relativePath>
|
<relativePath>../../parent-java</relativePath>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<commons-lang3.version>3.9</commons-lang3.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>junit</groupId>
|
<groupId>junit</groupId>
|
||||||
@ -21,6 +25,11 @@
|
|||||||
<version>4.12</version>
|
<version>4.12</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.commons</groupId>
|
||||||
|
<artifactId>commons-lang3</artifactId>
|
||||||
|
<version>${commons-lang3.version}</version>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
@ -1,7 +1,6 @@
|
|||||||
package com.baeldung.error;
|
package com.baeldung.exception.error;
|
||||||
|
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Before;
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class ErrorGeneratorUnitTest {
|
public class ErrorGeneratorUnitTest {
|
||||||
|
@ -1,3 +0,0 @@
|
|||||||
### Relevant Articles
|
|
||||||
|
|
||||||
- [Why Do Local Variables Used in Lambdas Have to Be Final or Effectively Final?](https://www.baeldung.com/java-lambda-effectively-final-local-variables)
|
|
@ -0,0 +1,25 @@
|
|||||||
|
package com.baeldung.rawtype;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class RawTypeDemo {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
RawTypeDemo rawTypeDemo = new RawTypeDemo();
|
||||||
|
rawTypeDemo.methodA();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void methodA() {
|
||||||
|
// parameterized type
|
||||||
|
List<String> listStr = new ArrayList<>();
|
||||||
|
listStr.add("Hello Folks!");
|
||||||
|
methodB(listStr);
|
||||||
|
String s = listStr.get(1); // ClassCastException at run time
|
||||||
|
}
|
||||||
|
|
||||||
|
public void methodB(List rawList) { // Inexpressive raw type
|
||||||
|
rawList.add(1); // Unsafe operation
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,47 @@
|
|||||||
|
package com.baeldung.breakloop;
|
||||||
|
|
||||||
|
public class LoopBreaking {
|
||||||
|
|
||||||
|
public String simpleBreak() {
|
||||||
|
String result = "";
|
||||||
|
for (int outerCounter = 0; outerCounter < 2; outerCounter++) {
|
||||||
|
result += "outer" + outerCounter;
|
||||||
|
for (int innerCounter = 0; innerCounter < 2; innerCounter++) {
|
||||||
|
result += "inner" + innerCounter;
|
||||||
|
if (innerCounter == 0) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String labelBreak() {
|
||||||
|
String result = "";
|
||||||
|
myBreakLabel:
|
||||||
|
for (int outerCounter = 0; outerCounter < 2; outerCounter++) {
|
||||||
|
result += "outer" + outerCounter;
|
||||||
|
for (int innerCounter = 0; innerCounter < 2; innerCounter++) {
|
||||||
|
result += "inner" + innerCounter;
|
||||||
|
if (innerCounter == 0) {
|
||||||
|
break myBreakLabel;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String usingReturn() {
|
||||||
|
String result = "";
|
||||||
|
for (int outerCounter = 0; outerCounter < 2; outerCounter++) {
|
||||||
|
result += "outer" + outerCounter;
|
||||||
|
for (int innerCounter = 0; innerCounter < 2; innerCounter++) {
|
||||||
|
result += "inner" + innerCounter;
|
||||||
|
if (innerCounter == 0) {
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "failed";
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,25 @@
|
|||||||
|
package com.baeldung.breakloop;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
class LoopBreakingUnitTest {
|
||||||
|
|
||||||
|
private LoopBreaking loopBreaking = new LoopBreaking();
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingBreak_shouldBreakInnerLoop() {
|
||||||
|
assertEquals("outer0inner0outer1inner0", loopBreaking.simpleBreak());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingLabeledBreak_shouldBreakInnerLoopAndOuterLoop() {
|
||||||
|
assertEquals("outer0inner0", loopBreaking.labelBreak());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingReturn_shouldBreakInnerLoopAndOuterLoop() {
|
||||||
|
assertEquals("outer0inner0", loopBreaking.usingReturn());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,36 @@
|
|||||||
|
package com.baeldung.random;
|
||||||
|
|
||||||
|
import java.security.SecureRandom;
|
||||||
|
import java.security.NoSuchAlgorithmException;
|
||||||
|
import java.util.stream.IntStream;
|
||||||
|
import java.util.stream.LongStream;
|
||||||
|
import java.util.stream.DoubleStream;
|
||||||
|
|
||||||
|
public interface SecureRandomDemo {
|
||||||
|
|
||||||
|
public static void generateSecureRandomValues() {
|
||||||
|
SecureRandom sr = new SecureRandom();
|
||||||
|
|
||||||
|
int randomInt = sr.nextInt();
|
||||||
|
long randomLong = sr.nextLong();
|
||||||
|
float randomFloat = sr.nextFloat();
|
||||||
|
double randomDouble = sr.nextDouble();
|
||||||
|
boolean randomBoolean = sr.nextBoolean();
|
||||||
|
|
||||||
|
IntStream randomIntStream = sr.ints();
|
||||||
|
LongStream randomLongStream = sr.longs();
|
||||||
|
DoubleStream randomDoubleStream = sr.doubles();
|
||||||
|
|
||||||
|
byte[] values = new byte[124];
|
||||||
|
sr.nextBytes(values);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static SecureRandom getSecureRandomForAlgorithm(String algorithm) throws NoSuchAlgorithmException {
|
||||||
|
if (algorithm == null || algorithm.isEmpty()) {
|
||||||
|
return new SecureRandom();
|
||||||
|
}
|
||||||
|
|
||||||
|
return SecureRandom.getInstance(algorithm);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
23
easy-random/pom.xml
Normal file
23
easy-random/pom.xml
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
<?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>easy-random</artifactId>
|
||||||
|
<name>easy-random</name>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<artifactId>parent-modules</artifactId>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.jeasy</groupId>
|
||||||
|
<artifactId>easy-random-core</artifactId>
|
||||||
|
<version>4.0.0</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
</project>
|
@ -0,0 +1,17 @@
|
|||||||
|
package org.baeldung.easy.random.model;
|
||||||
|
|
||||||
|
import java.util.StringJoiner;
|
||||||
|
|
||||||
|
public class Department {
|
||||||
|
private String depName;
|
||||||
|
|
||||||
|
public Department(String depName) {
|
||||||
|
this.depName = depName;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return new StringJoiner(", ", Department.class.getSimpleName() + "[", "]").add("depName='" + depName + "'")
|
||||||
|
.toString();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,70 @@
|
|||||||
|
package org.baeldung.easy.random.model;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
public class Employee {
|
||||||
|
|
||||||
|
private long id;
|
||||||
|
private String firstName;
|
||||||
|
private String lastName;
|
||||||
|
private Department department;
|
||||||
|
private Collection<Employee> coworkers;
|
||||||
|
private Map<YearQuarter, Grade> quarterGrades;
|
||||||
|
|
||||||
|
public Employee(long id, String firstName, String lastName, Department department) {
|
||||||
|
this.id = id;
|
||||||
|
this.firstName = firstName;
|
||||||
|
this.lastName = lastName;
|
||||||
|
this.department = department;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object o) {
|
||||||
|
if (this == o)
|
||||||
|
return true;
|
||||||
|
if (o == null || getClass() != o.getClass())
|
||||||
|
return false;
|
||||||
|
Employee employee = (Employee) o;
|
||||||
|
return id == employee.id;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
return Objects.hash(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getFirstName() {
|
||||||
|
return firstName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getLastName() {
|
||||||
|
return lastName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Department getDepartment() {
|
||||||
|
return department;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Collection<Employee> getCoworkers() {
|
||||||
|
return Collections.unmodifiableCollection(coworkers);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<YearQuarter, Grade> getQuarterGrades() {
|
||||||
|
return Collections.unmodifiableMap(quarterGrades);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return new StringJoiner(", ", Employee.class.getSimpleName() + "[", "]").add("id=" + id)
|
||||||
|
.add("firstName='" + firstName + "'")
|
||||||
|
.add("lastName='" + lastName + "'")
|
||||||
|
.add("department=" + department)
|
||||||
|
.add("coworkers size=" + ((coworkers == null) ? 0 : coworkers.size()))
|
||||||
|
.add("quarterGrades=" + quarterGrades)
|
||||||
|
.toString();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,22 @@
|
|||||||
|
package org.baeldung.easy.random.model;
|
||||||
|
|
||||||
|
import java.util.StringJoiner;
|
||||||
|
|
||||||
|
public class Grade {
|
||||||
|
|
||||||
|
private int grade;
|
||||||
|
|
||||||
|
public Grade(int grade) {
|
||||||
|
this.grade = grade;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getGrade() {
|
||||||
|
return grade;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return new StringJoiner(", ", Grade.class.getSimpleName() + "[", "]").add("grade=" + grade)
|
||||||
|
.toString();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,30 @@
|
|||||||
|
package org.baeldung.easy.random.model;
|
||||||
|
|
||||||
|
import java.util.StringJoiner;
|
||||||
|
|
||||||
|
public class Person {
|
||||||
|
|
||||||
|
private String firstName;
|
||||||
|
private String lastName;
|
||||||
|
private Integer age;
|
||||||
|
|
||||||
|
public String getFirstName() {
|
||||||
|
return firstName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getLastName() {
|
||||||
|
return lastName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Integer getAge() {
|
||||||
|
return age;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return new StringJoiner(", ", Person.class.getSimpleName() + "[", "]").add("firstName='" + firstName + "'")
|
||||||
|
.add("lastName='" + lastName + "'")
|
||||||
|
.add("age=" + age)
|
||||||
|
.toString();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,50 @@
|
|||||||
|
package org.baeldung.easy.random.model;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.StringJoiner;
|
||||||
|
|
||||||
|
public class YearQuarter {
|
||||||
|
|
||||||
|
private LocalDate startDate;
|
||||||
|
private LocalDate endDate;
|
||||||
|
|
||||||
|
public YearQuarter(LocalDate startDate) {
|
||||||
|
this.startDate = startDate;
|
||||||
|
autoAdjustEndDate();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void autoAdjustEndDate() {
|
||||||
|
endDate = startDate.plusMonths(3L);
|
||||||
|
}
|
||||||
|
|
||||||
|
public LocalDate getStartDate() {
|
||||||
|
return startDate;
|
||||||
|
}
|
||||||
|
|
||||||
|
public LocalDate getEndDate() {
|
||||||
|
return endDate;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object o) {
|
||||||
|
if (this == o)
|
||||||
|
return true;
|
||||||
|
if (o == null || getClass() != o.getClass())
|
||||||
|
return false;
|
||||||
|
YearQuarter quarter = (YearQuarter) o;
|
||||||
|
return Objects.equals(startDate, quarter.startDate) && Objects.equals(endDate, quarter.endDate);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
return Objects.hash(startDate, endDate);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return new StringJoiner(", ", YearQuarter.class.getSimpleName() + "[", "]").add("startDate=" + startDate)
|
||||||
|
.add("endDate=" + endDate)
|
||||||
|
.toString();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,18 @@
|
|||||||
|
package org.baeldung.easy.random.randomizer;
|
||||||
|
|
||||||
|
import org.baeldung.easy.random.model.YearQuarter;
|
||||||
|
import org.jeasy.random.api.Randomizer;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.Month;
|
||||||
|
|
||||||
|
public class YearQuarterRandomizer implements Randomizer<YearQuarter> {
|
||||||
|
|
||||||
|
private LocalDate date = LocalDate.of(1990, Month.SEPTEMBER, 25);
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public YearQuarter getRandomValue() {
|
||||||
|
date = date.plusMonths(3);
|
||||||
|
return new YearQuarter(date);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,63 @@
|
|||||||
|
package org.baeldung.easy.random;
|
||||||
|
|
||||||
|
import org.baeldung.easy.random.model.Employee;
|
||||||
|
import org.baeldung.easy.random.model.Person;
|
||||||
|
import org.baeldung.easy.random.model.YearQuarter;
|
||||||
|
import org.baeldung.easy.random.randomizer.YearQuarterRandomizer;
|
||||||
|
import org.jeasy.random.EasyRandom;
|
||||||
|
import org.jeasy.random.EasyRandomParameters;
|
||||||
|
import org.jeasy.random.FieldPredicates;
|
||||||
|
import org.jeasy.random.TypePredicates;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
class EasyRandomUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenDefaultConfiguration_thenGenerateSingleObject() {
|
||||||
|
EasyRandom generator = new EasyRandom();
|
||||||
|
Person person = generator.nextObject(Person.class);
|
||||||
|
|
||||||
|
assertNotNull(person.getAge());
|
||||||
|
assertNotNull(person.getFirstName());
|
||||||
|
assertNotNull(person.getLastName());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenDefaultConfiguration_thenGenerateObjectsList() {
|
||||||
|
EasyRandom generator = new EasyRandom();
|
||||||
|
List<Person> persons = generator.objects(Person.class, 5)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
|
assertEquals(5, persons.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenCustomConfiguration_thenGenerateSingleEmployee() {
|
||||||
|
EasyRandomParameters parameters = new EasyRandomParameters();
|
||||||
|
parameters.stringLengthRange(3, 3);
|
||||||
|
parameters.collectionSizeRange(5, 5);
|
||||||
|
parameters.excludeField(FieldPredicates.named("lastName").and(FieldPredicates.inClass(Employee.class)));
|
||||||
|
parameters.excludeType(TypePredicates.inPackage("not.existing.pkg"));
|
||||||
|
parameters.randomize(YearQuarter.class, new YearQuarterRandomizer());
|
||||||
|
|
||||||
|
EasyRandom generator = new EasyRandom(parameters);
|
||||||
|
Employee employee = generator.nextObject(Employee.class);
|
||||||
|
|
||||||
|
assertEquals(3, employee.getFirstName().length());
|
||||||
|
assertEquals(5, employee.getCoworkers().size());
|
||||||
|
assertEquals(5, employee.getQuarterGrades().size());
|
||||||
|
assertNotNull(employee.getDepartment());
|
||||||
|
|
||||||
|
assertNull(employee.getLastName());
|
||||||
|
|
||||||
|
for (YearQuarter key : employee.getQuarterGrades().keySet()) {
|
||||||
|
assertEquals(key.getStartDate(), key.getEndDate().minusMonths(3L));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,100 @@
|
|||||||
|
package com.baeldung.convert.iteratortolist;
|
||||||
|
|
||||||
|
import static org.hamcrest.MatcherAssert.assertThat;
|
||||||
|
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
|
||||||
|
import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Iterator;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.StreamSupport;
|
||||||
|
|
||||||
|
import org.apache.commons.collections4.IteratorUtils;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.google.common.collect.ImmutableList;
|
||||||
|
import com.google.common.collect.Lists;
|
||||||
|
|
||||||
|
public class ConvertIteratorToListServiceUnitTest {
|
||||||
|
|
||||||
|
Iterator<Integer> iterator;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setUp() throws Exception {
|
||||||
|
iterator = Arrays.asList(1, 2, 3)
|
||||||
|
.iterator();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAnIterator_whenConvertIteratorToListUsingWhileLoop_thenReturnAList() {
|
||||||
|
|
||||||
|
List<Integer> actualList = new ArrayList<Integer>();
|
||||||
|
|
||||||
|
// Convert Iterator to List using while loop dsf
|
||||||
|
while (iterator.hasNext()) {
|
||||||
|
actualList.add(iterator.next());
|
||||||
|
}
|
||||||
|
|
||||||
|
assertThat(actualList, hasSize(3));
|
||||||
|
assertThat(actualList, containsInAnyOrder(1, 2, 3));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAnIterator_whenConvertIteratorToListAfterJava8_thenReturnAList() {
|
||||||
|
List<Integer> actualList = new ArrayList<Integer>();
|
||||||
|
|
||||||
|
// Convert Iterator to List using Java 8
|
||||||
|
iterator.forEachRemaining(actualList::add);
|
||||||
|
|
||||||
|
assertThat(actualList, hasSize(3));
|
||||||
|
assertThat(actualList, containsInAnyOrder(1, 2, 3));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAnIterator_whenConvertIteratorToListJava8Stream_thenReturnAList() {
|
||||||
|
|
||||||
|
// Convert iterator to iterable
|
||||||
|
Iterable<Integer> iterable = () -> iterator;
|
||||||
|
|
||||||
|
// Extract List from stream
|
||||||
|
List<Integer> actualList = StreamSupport
|
||||||
|
.stream(iterable.spliterator(), false)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
|
assertThat(actualList, hasSize(3));
|
||||||
|
assertThat(actualList, containsInAnyOrder(1, 2, 3));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAnIterator_whenConvertIteratorToImmutableListWithGuava_thenReturnAList() {
|
||||||
|
|
||||||
|
// Convert Iterator to an Immutable list using Guava library in Java
|
||||||
|
List<Integer> actualList = ImmutableList.copyOf(iterator);
|
||||||
|
|
||||||
|
assertThat(actualList, hasSize(3));
|
||||||
|
assertThat(actualList, containsInAnyOrder(1, 2, 3));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAnIterator_whenConvertIteratorToMutableListWithGuava_thenReturnAList() {
|
||||||
|
|
||||||
|
// Convert Iterator to a mutable list using Guava library in Java
|
||||||
|
List<Integer> actualList = Lists.newArrayList(iterator);
|
||||||
|
|
||||||
|
assertThat(actualList, hasSize(3));
|
||||||
|
assertThat(actualList, containsInAnyOrder(1, 2, 3));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAnIterator_whenConvertIteratorToMutableListWithApacheCommons_thenReturnAList() {
|
||||||
|
|
||||||
|
// Convert Iterator to a mutable list using Apache Commons library in Java
|
||||||
|
List<Integer> actualList = IteratorUtils.toList(iterator);
|
||||||
|
|
||||||
|
assertThat(actualList, hasSize(3));
|
||||||
|
assertThat(actualList, containsInAnyOrder(1, 2, 3));
|
||||||
|
}
|
||||||
|
}
|
@ -21,6 +21,13 @@
|
|||||||
<version>${joda-time.version}</version>
|
<version>${joda-time.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<!-- https://mvnrepository.com/artifact/commons-validator/commons-validator -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>commons-validator</groupId>
|
||||||
|
<artifactId>commons-validator</artifactId>
|
||||||
|
<version>1.6</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
<!-- test scoped -->
|
<!-- test scoped -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.assertj</groupId>
|
<groupId>org.assertj</groupId>
|
||||||
|
@ -0,0 +1,5 @@
|
|||||||
|
package com.baeldung.date.validation;
|
||||||
|
|
||||||
|
public interface DateValidator {
|
||||||
|
boolean isValid(String dateStr);
|
||||||
|
}
|
@ -0,0 +1,11 @@
|
|||||||
|
package com.baeldung.date.validation;
|
||||||
|
|
||||||
|
import org.apache.commons.validator.GenericValidator;
|
||||||
|
|
||||||
|
public class DateValidatorUsingApacheValidator implements DateValidator {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isValid(String dateStr) {
|
||||||
|
return GenericValidator.isDate(dateStr, "yyyy-MM-dd", true);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,25 @@
|
|||||||
|
package com.baeldung.date.validation;
|
||||||
|
|
||||||
|
import java.text.DateFormat;
|
||||||
|
import java.text.ParseException;
|
||||||
|
import java.text.SimpleDateFormat;
|
||||||
|
|
||||||
|
public class DateValidatorUsingDateFormat implements DateValidator {
|
||||||
|
private String dateFormat;
|
||||||
|
|
||||||
|
public DateValidatorUsingDateFormat(String dateFormat) {
|
||||||
|
this.dateFormat = dateFormat;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isValid(String dateStr) {
|
||||||
|
DateFormat sdf = new SimpleDateFormat(this.dateFormat);
|
||||||
|
sdf.setLenient(false);
|
||||||
|
try {
|
||||||
|
sdf.parse(dateStr);
|
||||||
|
} catch (ParseException e) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,22 @@
|
|||||||
|
package com.baeldung.date.validation;
|
||||||
|
|
||||||
|
import java.time.format.DateTimeFormatter;
|
||||||
|
import java.time.format.DateTimeParseException;
|
||||||
|
|
||||||
|
public class DateValidatorUsingDateTimeFormatter implements DateValidator {
|
||||||
|
private DateTimeFormatter dateFormatter;
|
||||||
|
|
||||||
|
public DateValidatorUsingDateTimeFormatter(DateTimeFormatter dateFormatter) {
|
||||||
|
this.dateFormatter = dateFormatter;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isValid(String dateStr) {
|
||||||
|
try {
|
||||||
|
this.dateFormatter.parse(dateStr);
|
||||||
|
} catch (DateTimeParseException e) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,23 @@
|
|||||||
|
package com.baeldung.date.validation;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.format.DateTimeFormatter;
|
||||||
|
import java.time.format.DateTimeParseException;
|
||||||
|
|
||||||
|
public class DateValidatorUsingLocalDate implements DateValidator {
|
||||||
|
private DateTimeFormatter dateFormatter;
|
||||||
|
|
||||||
|
public DateValidatorUsingLocalDate(DateTimeFormatter dateFormatter) {
|
||||||
|
this.dateFormatter = dateFormatter;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isValid(String dateStr) {
|
||||||
|
try {
|
||||||
|
LocalDate.parse(dateStr, this.dateFormatter);
|
||||||
|
} catch (DateTimeParseException e) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,20 @@
|
|||||||
|
package com.baeldung.date.validation;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import org.apache.commons.validator.GenericValidator;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class DateValidatorUsingApacheValidatorUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenValidDatePassed_ThenTrue() {
|
||||||
|
assertTrue(GenericValidator.isDate("2019-02-28", "yyyy-MM-dd", true));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenInvalidDatePassed_ThenFalse() {
|
||||||
|
assertFalse(GenericValidator.isDate("2019-02-29", "yyyy-MM-dd", true));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,23 @@
|
|||||||
|
package com.baeldung.date.validation;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class DateValidatorUsingDateFormatUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenValidator_whenValidDatePassed_ThenTrue() {
|
||||||
|
DateValidator validator = new DateValidatorUsingDateFormat("MM/dd/yyyy");
|
||||||
|
|
||||||
|
assertTrue(validator.isValid("02/28/2019"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenValidator_whenInvalidDatePassed_ThenFalse() {
|
||||||
|
DateValidator validator = new DateValidatorUsingDateFormat("MM/dd/yyyy");
|
||||||
|
|
||||||
|
assertFalse(validator.isValid("02/30/2019"));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,32 @@
|
|||||||
|
package com.baeldung.date.validation;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import java.time.format.DateTimeFormatter;
|
||||||
|
import java.time.format.ResolverStyle;
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class DateValidatorUsingDateTimeFormatterUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenValidator_whenValidDatePassed_ThenTrue() {
|
||||||
|
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("uuuu-MM-dd", Locale.US)
|
||||||
|
.withResolverStyle(ResolverStyle.STRICT);
|
||||||
|
DateValidator validator = new DateValidatorUsingDateTimeFormatter(dateFormatter);
|
||||||
|
|
||||||
|
assertTrue(validator.isValid("2019-02-28"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenValidator_whenInValidDatePassed_ThenFalse() {
|
||||||
|
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("uuuu-MM-dd", Locale.US)
|
||||||
|
.withResolverStyle(ResolverStyle.STRICT);
|
||||||
|
DateValidator validator = new DateValidatorUsingDateTimeFormatter(dateFormatter);
|
||||||
|
|
||||||
|
assertFalse(validator.isValid("2019-02-30"));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,27 @@
|
|||||||
|
package com.baeldung.date.validation;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import java.time.format.DateTimeFormatter;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class DateValidatorUsingLocalDateUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenValidator_whenValidDatePassed_ThenTrue() {
|
||||||
|
DateTimeFormatter dateFormatter = DateTimeFormatter.BASIC_ISO_DATE;
|
||||||
|
DateValidator validator = new DateValidatorUsingLocalDate(dateFormatter);
|
||||||
|
|
||||||
|
assertTrue(validator.isValid("20190228"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenValidator_whenInValidDatePassed_ThenFalse() {
|
||||||
|
DateTimeFormatter dateFormatter = DateTimeFormatter.BASIC_ISO_DATE;
|
||||||
|
DateValidator validator = new DateValidatorUsingLocalDate(dateFormatter);
|
||||||
|
|
||||||
|
assertFalse(validator.isValid("20190230"));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,36 @@
|
|||||||
|
package com.baeldung.random;
|
||||||
|
|
||||||
|
import java.security.SecureRandom;
|
||||||
|
import java.security.NoSuchAlgorithmException;
|
||||||
|
import java.util.stream.IntStream;
|
||||||
|
import java.util.stream.LongStream;
|
||||||
|
import java.util.stream.DoubleStream;
|
||||||
|
|
||||||
|
public interface SecureRandomDemo {
|
||||||
|
|
||||||
|
public static void generateSecureRandomValues() {
|
||||||
|
SecureRandom sr = new SecureRandom();
|
||||||
|
|
||||||
|
int randomInt = sr.nextInt();
|
||||||
|
long randomLong = sr.nextLong();
|
||||||
|
float randomFloat = sr.nextFloat();
|
||||||
|
double randomDouble = sr.nextDouble();
|
||||||
|
boolean randomBoolean = sr.nextBoolean();
|
||||||
|
|
||||||
|
IntStream randomIntStream = sr.ints();
|
||||||
|
LongStream randomLongStream = sr.longs();
|
||||||
|
DoubleStream randomDoubleStream = sr.doubles();
|
||||||
|
|
||||||
|
byte[] values = new byte[124];
|
||||||
|
sr.nextBytes(values);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static SecureRandom getSecureRandomForAlgorithm(String algorithm) throws NoSuchAlgorithmException {
|
||||||
|
if (algorithm == null || algorithm.isEmpty()) {
|
||||||
|
return new SecureRandom();
|
||||||
|
}
|
||||||
|
|
||||||
|
return SecureRandom.getInstance(algorithm);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -4,7 +4,7 @@
|
|||||||
<groupId>com.baeldung.javastreams2</groupId>
|
<groupId>com.baeldung.javastreams2</groupId>
|
||||||
<artifactId>javastreams2</artifactId>
|
<artifactId>javastreams2</artifactId>
|
||||||
<version>1.0</version>
|
<version>1.0</version>
|
||||||
<name>Stream Reduce</name>
|
<name>javastreams2</name>
|
||||||
<packaging>jar</packaging>
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
@ -42,8 +42,8 @@
|
|||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
<maven.compiler.source>1.8</maven.compiler.source>
|
<maven.compiler.source>1.9</maven.compiler.source>
|
||||||
<maven.compiler.target>1.8</maven.compiler.target>
|
<maven.compiler.target>1.9</maven.compiler.target>
|
||||||
<assertj.version>3.11.1</assertj.version>
|
<assertj.version>3.11.1</assertj.version>
|
||||||
</properties>
|
</properties>
|
||||||
</project>
|
</project>
|
@ -0,0 +1,32 @@
|
|||||||
|
package com.baeldung.breakforeach;
|
||||||
|
|
||||||
|
import java.util.Spliterator;
|
||||||
|
import java.util.function.BiConsumer;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
public class CustomForEach {
|
||||||
|
|
||||||
|
public static class Breaker {
|
||||||
|
private boolean shouldBreak = false;
|
||||||
|
|
||||||
|
public void stop() {
|
||||||
|
shouldBreak = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean get() {
|
||||||
|
return shouldBreak;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static <T> void forEach(Stream<T> stream, BiConsumer<T, Breaker> consumer) {
|
||||||
|
Spliterator<T> spliterator = stream.spliterator();
|
||||||
|
boolean hadNext = true;
|
||||||
|
Breaker breaker = new Breaker();
|
||||||
|
|
||||||
|
while (hadNext && !breaker.get()) {
|
||||||
|
hadNext = spliterator.tryAdvance(elem -> {
|
||||||
|
consumer.accept(elem, breaker);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,31 @@
|
|||||||
|
package com.baeldung.breakforeach;
|
||||||
|
|
||||||
|
import java.util.Spliterator;
|
||||||
|
import java.util.Spliterators;
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
import java.util.function.Predicate;
|
||||||
|
|
||||||
|
public class CustomSpliterator<T> extends Spliterators.AbstractSpliterator<T> {
|
||||||
|
|
||||||
|
private Spliterator<T> splitr;
|
||||||
|
private Predicate<T> predicate;
|
||||||
|
private boolean isMatched = true;
|
||||||
|
|
||||||
|
public CustomSpliterator(Spliterator<T> splitr, Predicate<T> predicate) {
|
||||||
|
super(splitr.estimateSize(), 0);
|
||||||
|
this.splitr = splitr;
|
||||||
|
this.predicate = predicate;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean tryAdvance(Consumer<? super T> consumer) {
|
||||||
|
boolean hadNext = splitr.tryAdvance(elem -> {
|
||||||
|
if (predicate.test(elem) && isMatched) {
|
||||||
|
consumer.accept(elem);
|
||||||
|
} else {
|
||||||
|
isMatched = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return hadNext && isMatched;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,14 @@
|
|||||||
|
package com.baeldung.breakforeach;
|
||||||
|
|
||||||
|
import java.util.function.Predicate;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
import java.util.stream.StreamSupport;
|
||||||
|
|
||||||
|
public class CustomTakeWhile {
|
||||||
|
|
||||||
|
public static <T> Stream<T> takeWhile(Stream<T> stream, Predicate<T> predicate) {
|
||||||
|
CustomSpliterator<T> customSpliterator = new CustomSpliterator<>(stream.spliterator(), predicate);
|
||||||
|
return StreamSupport.stream(customSpliterator, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,26 @@
|
|||||||
|
package com.baeldung.breakforeach;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import static java.util.Arrays.asList;
|
||||||
|
|
||||||
|
public class TakeWhileExample {
|
||||||
|
|
||||||
|
public static void takeWhileJava9() {
|
||||||
|
Stream.of("cat", "dog", "elephant", "fox", "rabbit", "duck")
|
||||||
|
.takeWhile(n -> n.length() % 2 != 0)
|
||||||
|
.forEach(System.out::println); // cat, dog
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void plainForLoopWithBreak() {
|
||||||
|
List<String> list = asList("cat", "dog", "elephant", "fox", "rabbit", "duck");
|
||||||
|
for (int i = 0; i < list.size(); i++) {
|
||||||
|
String item = list.get(i);
|
||||||
|
if (item.length() % 2 == 0) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
System.out.println(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,41 @@
|
|||||||
|
package com.baeldung.breakforeach;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import static java.util.Arrays.asList;
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
public class BreakFromStreamForEachUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCustomTakeWhileIsCalled_ThenCorrectItemsAreReturned() {
|
||||||
|
Stream<String> initialStream = Stream.of("cat", "dog", "elephant", "fox", "rabbit", "duck");
|
||||||
|
|
||||||
|
List<String> result = CustomTakeWhile.takeWhile(initialStream, x -> x.length() % 2 != 0)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
|
assertEquals(asList("cat", "dog"), result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCustomForEachIsCalled_ThenCorrectItemsAreReturned() {
|
||||||
|
Stream<String> initialStream = Stream.of("cat", "dog", "elephant", "fox", "rabbit", "duck");
|
||||||
|
List<String> result = new ArrayList<>();
|
||||||
|
|
||||||
|
CustomForEach.forEach(initialStream, (elem, breaker) -> {
|
||||||
|
if (elem.length() % 2 == 0) {
|
||||||
|
breaker.stop();
|
||||||
|
} else {
|
||||||
|
result.add(elem);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
assertEquals(asList("cat", "dog"), result);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,40 @@
|
|||||||
|
package com.baeldung.convert.intstreams;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.IntStream;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
public class IntStreamsConversionsUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void intStreamToArray() {
|
||||||
|
int[] first50EvenNumbers = IntStream.iterate(0, i -> i + 2)
|
||||||
|
.limit(50)
|
||||||
|
.toArray();
|
||||||
|
|
||||||
|
assertThat(first50EvenNumbers).hasSize(50);
|
||||||
|
assertThat(first50EvenNumbers[2]).isEqualTo(4);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void intStreamToList() {
|
||||||
|
List<Integer> first50IntegerNumbers = IntStream.range(0, 50)
|
||||||
|
.boxed()
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
|
assertThat(first50IntegerNumbers).hasSize(50);
|
||||||
|
assertThat(first50IntegerNumbers.get(2)).isEqualTo(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void intStreamToString() {
|
||||||
|
String first3numbers = IntStream.of(0, 1, 2)
|
||||||
|
.mapToObj(String::valueOf)
|
||||||
|
.collect(Collectors.joining(", ", "[", "]"));
|
||||||
|
|
||||||
|
assertThat(first3numbers).isEqualTo("[0, 1, 2]");
|
||||||
|
}
|
||||||
|
}
|
@ -3,3 +3,4 @@
|
|||||||
- [Java Localization – Formatting Messages](https://www.baeldung.com/java-localization-messages-formatting)
|
- [Java Localization – Formatting Messages](https://www.baeldung.com/java-localization-messages-formatting)
|
||||||
- [Check If a String Contains a Substring](https://www.baeldung.com/java-string-contains-substring)
|
- [Check If a String Contains a Substring](https://www.baeldung.com/java-string-contains-substring)
|
||||||
- [Removing Stopwords from a String in Java](https://www.baeldung.com/java-string-remove-stopwords)
|
- [Removing Stopwords from a String in Java](https://www.baeldung.com/java-string-remove-stopwords)
|
||||||
|
- [Blank and Empty Strings in Java](https://www.baeldung.com/java-blank-empty-strings)
|
||||||
|
@ -57,6 +57,26 @@
|
|||||||
<artifactId>commons-text</artifactId>
|
<artifactId>commons-text</artifactId>
|
||||||
<version>${commons-text.version}</version>
|
<version>${commons-text.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>javax.validation</groupId>
|
||||||
|
<artifactId>validation-api</artifactId>
|
||||||
|
<version>2.0.0.Final</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.hibernate.validator</groupId>
|
||||||
|
<artifactId>hibernate-validator</artifactId>
|
||||||
|
<version>6.0.2.Final</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>javax.el</groupId>
|
||||||
|
<artifactId>javax.el-api</artifactId>
|
||||||
|
<version>3.0.0</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.glassfish.web</groupId>
|
||||||
|
<artifactId>javax.el</artifactId>
|
||||||
|
<version>2.2.6</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
@ -86,7 +106,7 @@
|
|||||||
<properties>
|
<properties>
|
||||||
<commons-lang3.version>3.8.1</commons-lang3.version>
|
<commons-lang3.version>3.8.1</commons-lang3.version>
|
||||||
<icu4j.version>61.1</icu4j.version>
|
<icu4j.version>61.1</icu4j.version>
|
||||||
<guava.version>27.0.1-jre</guava.version>
|
<guava.version>28.0-jre</guava.version>
|
||||||
<commons-text.version>1.4</commons-text.version>
|
<commons-text.version>1.4</commons-text.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
|
@ -0,0 +1,8 @@
|
|||||||
|
package com.baeldung.string.emptystrings;
|
||||||
|
|
||||||
|
class EmptyStringCheck {
|
||||||
|
|
||||||
|
boolean isEmptyString(String string) {
|
||||||
|
return string == null || string.isEmpty();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,8 @@
|
|||||||
|
package com.baeldung.string.emptystrings;
|
||||||
|
|
||||||
|
class Java5EmptyStringCheck {
|
||||||
|
|
||||||
|
boolean isEmptyString(String string) {
|
||||||
|
return string == null || string.length() == 0;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,8 @@
|
|||||||
|
package com.baeldung.string.emptystrings;
|
||||||
|
|
||||||
|
class PlainJavaBlankStringCheck {
|
||||||
|
|
||||||
|
boolean isBlankString(String string) {
|
||||||
|
return string == null || string.trim().isEmpty();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,14 @@
|
|||||||
|
package com.baeldung.string.emptystrings;
|
||||||
|
|
||||||
|
import javax.validation.constraints.Pattern;
|
||||||
|
|
||||||
|
class SomeClassWithValidations {
|
||||||
|
|
||||||
|
@Pattern(regexp = "\\A(?!\\s*\\Z).+")
|
||||||
|
private String someString;
|
||||||
|
|
||||||
|
SomeClassWithValidations setSomeString(String someString) {
|
||||||
|
this.someString = someString;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,67 @@
|
|||||||
|
package com.baeldung.string.multiline;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.PrintWriter;
|
||||||
|
import java.io.StringWriter;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
|
||||||
|
import com.google.common.base.Joiner;
|
||||||
|
import com.google.common.collect.ImmutableList;
|
||||||
|
|
||||||
|
public class MultiLineString {
|
||||||
|
|
||||||
|
String newLine = System.getProperty("line.separator");
|
||||||
|
|
||||||
|
public String stringConcatenation() {
|
||||||
|
return "Get busy living"
|
||||||
|
.concat(newLine)
|
||||||
|
.concat("or")
|
||||||
|
.concat(newLine)
|
||||||
|
.concat("get busy dying.")
|
||||||
|
.concat(newLine)
|
||||||
|
.concat("--Stephen King");
|
||||||
|
}
|
||||||
|
|
||||||
|
public String stringJoin() {
|
||||||
|
return String.join(newLine,
|
||||||
|
"Get busy living",
|
||||||
|
"or",
|
||||||
|
"get busy dying.",
|
||||||
|
"--Stephen King");
|
||||||
|
}
|
||||||
|
|
||||||
|
public String stringBuilder() {
|
||||||
|
return new StringBuilder()
|
||||||
|
.append("Get busy living")
|
||||||
|
.append(newLine)
|
||||||
|
.append("or")
|
||||||
|
.append(newLine)
|
||||||
|
.append("get busy dying.")
|
||||||
|
.append(newLine)
|
||||||
|
.append("--Stephen King")
|
||||||
|
.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public String stringWriter() {
|
||||||
|
StringWriter stringWriter = new StringWriter();
|
||||||
|
PrintWriter printWriter = new PrintWriter(stringWriter);
|
||||||
|
printWriter.println("Get busy living");
|
||||||
|
printWriter.println("or");
|
||||||
|
printWriter.println("get busy dying.");
|
||||||
|
printWriter.println("--Stephen King");
|
||||||
|
return stringWriter.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public String guavaJoiner() {
|
||||||
|
return Joiner.on(newLine).join(ImmutableList.of("Get busy living",
|
||||||
|
"or",
|
||||||
|
"get busy dying.",
|
||||||
|
"--Stephen King"));
|
||||||
|
}
|
||||||
|
|
||||||
|
public String loadFromFile() throws IOException {
|
||||||
|
return new String(Files.readAllBytes(Paths.get("src/main/resources/stephenking.txt")));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,29 @@
|
|||||||
|
package com.baeldung.string.repetition;
|
||||||
|
|
||||||
|
public class SubstringRepetition {
|
||||||
|
|
||||||
|
public static boolean containsOnlySubstrings(String string) {
|
||||||
|
|
||||||
|
if (string.length() < 2) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
StringBuilder substr = new StringBuilder();
|
||||||
|
for (int i = 0; i < string.length() / 2; i++) {
|
||||||
|
substr.append(string.charAt(i));
|
||||||
|
|
||||||
|
String clearedFromSubstrings = string.replaceAll(substr.toString(), "");
|
||||||
|
|
||||||
|
if (clearedFromSubstrings.length() == 0) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean containsOnlySubstringsEfficient(String string) {
|
||||||
|
|
||||||
|
return ((string + string).indexOf(string, 1) != string.length());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,56 @@
|
|||||||
|
package com.baeldung.string.reverse;
|
||||||
|
|
||||||
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
|
||||||
|
public class ReverseStringExamples {
|
||||||
|
|
||||||
|
public static String reverse(String input) {
|
||||||
|
if (input == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
String output = "";
|
||||||
|
|
||||||
|
for (int i = input.length() - 1; i >= 0; i--) {
|
||||||
|
output = output + input.charAt(i);
|
||||||
|
}
|
||||||
|
|
||||||
|
return output;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String reverseUsingStringBuilder(String input) {
|
||||||
|
if (input == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
StringBuilder output = new StringBuilder(input).reverse();
|
||||||
|
|
||||||
|
return output.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String reverseUsingApacheCommons(String input) {
|
||||||
|
return StringUtils.reverse(input);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String reverseTheOrderOfWords(String sentence) {
|
||||||
|
if (sentence == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
StringBuilder output = new StringBuilder();
|
||||||
|
String[] words = sentence.split(" ");
|
||||||
|
|
||||||
|
for (int i = words.length - 1; i >= 0; i--) {
|
||||||
|
output.append(words[i]);
|
||||||
|
output.append(" ");
|
||||||
|
}
|
||||||
|
|
||||||
|
return output.toString()
|
||||||
|
.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String reverseTheOrderOfWordsUsingApacheCommons(String sentence) {
|
||||||
|
return StringUtils.reverseDelimited(sentence, ' ');
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
4
java-strings-2/src/main/resources/stephenking.txt
Normal file
4
java-strings-2/src/main/resources/stephenking.txt
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
Get busy living
|
||||||
|
or
|
||||||
|
get busy dying.
|
||||||
|
--Stephen King
|
@ -0,0 +1,22 @@
|
|||||||
|
package com.baeldung.string;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
import com.baeldung.string.multiline.MultiLineString;
|
||||||
|
|
||||||
|
public class MultiLineStringUnitTest {
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCompareMultiLineStrings_thenTheyAreAllTheSame() throws IOException {
|
||||||
|
MultiLineString ms = new MultiLineString();
|
||||||
|
assertEquals(ms.stringConcatenation(), ms.stringJoin());
|
||||||
|
assertEquals(ms.stringJoin(), ms.stringBuilder());
|
||||||
|
assertEquals(ms.stringBuilder(), ms.guavaJoiner());
|
||||||
|
assertEquals(ms.guavaJoiner(), ms.loadFromFile());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,142 @@
|
|||||||
|
package com.baeldung.string.emptystrings;
|
||||||
|
|
||||||
|
import static org.hamcrest.Matchers.iterableWithSize;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertThat;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
import javax.validation.ConstraintViolation;
|
||||||
|
import javax.validation.Validation;
|
||||||
|
import javax.validation.Validator;
|
||||||
|
import javax.validation.ValidatorFactory;
|
||||||
|
|
||||||
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.google.common.base.Strings;
|
||||||
|
|
||||||
|
public class EmptyStringsUnitTest {
|
||||||
|
|
||||||
|
private String emptyString = "";
|
||||||
|
private String blankString = " \n\t ";
|
||||||
|
private String nonEmptyString = " someString ";
|
||||||
|
|
||||||
|
/*
|
||||||
|
* EmptyStringCheck
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
public void givenSomeEmptyString_thenEmptyStringCheckIsEmptyStringReturnsTrue() {
|
||||||
|
assertTrue(new EmptyStringCheck().isEmptyString(emptyString));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSomeNonEmptyString_thenEmptyStringCheckIsEmptyStringReturnsFalse() {
|
||||||
|
assertFalse(new EmptyStringCheck().isEmptyString(nonEmptyString));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSomeBlankString_thenEmptyStringCheckIsEmptyStringReturnsFalse() {
|
||||||
|
assertFalse(new EmptyStringCheck().isEmptyString(blankString));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Java5EmptyStringCheck
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
public void givenSomeEmptyString_thenJava5EmptyStringCheckIsEmptyStringReturnsTrue() {
|
||||||
|
assertTrue(new Java5EmptyStringCheck().isEmptyString(emptyString));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSomeNonEmptyString_thenJava5EmptyStringCheckIsEmptyStringReturnsFalse() {
|
||||||
|
assertFalse(new Java5EmptyStringCheck().isEmptyString(nonEmptyString));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSomeBlankString_thenJava5EmptyStringCheckIsEmptyStringReturnsFalse() {
|
||||||
|
assertFalse(new Java5EmptyStringCheck().isEmptyString(blankString));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* PlainJavaBlankStringCheck
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
public void givenSomeEmptyString_thenPlainJavaBlankStringCheckIsBlankStringReturnsTrue() {
|
||||||
|
assertTrue(new PlainJavaBlankStringCheck().isBlankString(emptyString));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSomeNonEmptyString_thenPlainJavaBlankStringCheckIsBlankStringReturnsFalse() {
|
||||||
|
assertFalse(new PlainJavaBlankStringCheck().isBlankString(nonEmptyString));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSomeBlankString_thenPlainJavaBlankStringCheckIsBlankStringReturnsTrue() {
|
||||||
|
assertTrue(new PlainJavaBlankStringCheck().isBlankString(blankString));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Apache Commons Lang StringUtils
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
public void givenSomeEmptyString_thenStringUtilsIsBlankReturnsTrue() {
|
||||||
|
assertTrue(StringUtils.isBlank(emptyString));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSomeNonEmptyString_thenStringUtilsIsBlankReturnsFalse() {
|
||||||
|
assertFalse(StringUtils.isBlank(nonEmptyString));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSomeBlankString_thenStringUtilsIsBlankReturnsTrue() {
|
||||||
|
assertTrue(StringUtils.isBlank(blankString));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Google Guava Strings
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
public void givenSomeEmptyString_thenStringsIsNullOrEmptyStringReturnsTrue() {
|
||||||
|
assertTrue(Strings.isNullOrEmpty(emptyString));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSomeNonEmptyString_thenStringsIsNullOrEmptyStringReturnsFalse() {
|
||||||
|
assertFalse(Strings.isNullOrEmpty(nonEmptyString));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSomeBlankString_thenStringsIsNullOrEmptyStringReturnsFalse() {
|
||||||
|
assertFalse(Strings.isNullOrEmpty(blankString));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Bean Validation
|
||||||
|
*/
|
||||||
|
private ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
|
||||||
|
private Validator validator = factory.getValidator();
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSomeEmptyString_thenBeanValidationReturnsViolations() {
|
||||||
|
SomeClassWithValidations someClassWithValidations = new SomeClassWithValidations().setSomeString(emptyString);
|
||||||
|
Set<ConstraintViolation<SomeClassWithValidations>> violations = validator.validate(someClassWithValidations);
|
||||||
|
assertThat(violations, iterableWithSize(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSomeNonEmptyString_thenBeanValidationValidatesWithoutViolations() {
|
||||||
|
SomeClassWithValidations someClassWithValidations = new SomeClassWithValidations().setSomeString(nonEmptyString);
|
||||||
|
Set<ConstraintViolation<SomeClassWithValidations>> violations = validator.validate(someClassWithValidations);
|
||||||
|
assertThat(violations, iterableWithSize(0));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSomeBlankString_thenBeanValidationReturnsViolations() {
|
||||||
|
SomeClassWithValidations someClassWithValidations = new SomeClassWithValidations().setSomeString(blankString);
|
||||||
|
Set<ConstraintViolation<SomeClassWithValidations>> violations = validator.validate(someClassWithValidations);
|
||||||
|
assertThat(violations, iterableWithSize(1));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,45 @@
|
|||||||
|
package com.baeldung.string.repetition;
|
||||||
|
|
||||||
|
import static com.baeldung.string.repetition.SubstringRepetition.*;
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class SubstringRepetitionUnitTest {
|
||||||
|
|
||||||
|
private String validString = "aa";
|
||||||
|
private String validStringTwo = "ababab";
|
||||||
|
private String validStringThree = "baeldungbaeldung";
|
||||||
|
|
||||||
|
private String invalidString = "aca";
|
||||||
|
private String invalidStringTwo = "ababa";
|
||||||
|
private String invalidStringThree = "baeldungnonrepeatedbaeldung";
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenValidStrings_whenCheckIfContainsOnlySubstrings_thenReturnsTrue() {
|
||||||
|
assertTrue(containsOnlySubstrings(validString));
|
||||||
|
assertTrue(containsOnlySubstrings(validStringTwo));
|
||||||
|
assertTrue(containsOnlySubstrings(validStringThree));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenInvalidStrings_whenCheckIfContainsOnlySubstrings_thenReturnsFalse() {
|
||||||
|
assertFalse(containsOnlySubstrings(invalidString));
|
||||||
|
assertFalse(containsOnlySubstrings(invalidStringTwo));
|
||||||
|
assertFalse(containsOnlySubstrings(invalidStringThree));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenValidStrings_whenCheckEfficientlyIfContainsOnlySubstrings_thenReturnsTrue() {
|
||||||
|
assertTrue(containsOnlySubstringsEfficient(validString));
|
||||||
|
assertTrue(containsOnlySubstringsEfficient(validStringTwo));
|
||||||
|
assertTrue(containsOnlySubstringsEfficient(validStringThree));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenInvalidStrings_whenCheckEfficientlyIfContainsOnlySubstrings_thenReturnsFalse() {
|
||||||
|
assertFalse(containsOnlySubstringsEfficient(invalidString));
|
||||||
|
assertFalse(containsOnlySubstringsEfficient(invalidStringTwo));
|
||||||
|
assertFalse(containsOnlySubstringsEfficient(invalidStringThree));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,70 @@
|
|||||||
|
package com.baeldung.string.reverse;
|
||||||
|
|
||||||
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
public class ReverseStringExamplesUnitTest {
|
||||||
|
|
||||||
|
private static final String STRING_INPUT = "cat";
|
||||||
|
private static final String STRING_INPUT_REVERSED = "tac";
|
||||||
|
private static final String SENTENCE = "The quick brown fox jumps over the lazy dog";
|
||||||
|
private static final String REVERSED_WORDS_SENTENCE = "dog lazy the over jumps fox brown quick The";
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenReverseIsCalled_ThenCorrectStringIsReturned() {
|
||||||
|
String reversed = ReverseStringExamples.reverse(STRING_INPUT);
|
||||||
|
String reversedNull = ReverseStringExamples.reverse(null);
|
||||||
|
String reversedEmpty = ReverseStringExamples.reverse(StringUtils.EMPTY);
|
||||||
|
|
||||||
|
assertEquals(STRING_INPUT_REVERSED, reversed);
|
||||||
|
assertEquals(null, reversedNull);
|
||||||
|
assertEquals(StringUtils.EMPTY, reversedEmpty);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenReverseUsingStringBuilderIsCalled_ThenCorrectStringIsReturned() throws Exception {
|
||||||
|
String reversed = ReverseStringExamples.reverseUsingStringBuilder(STRING_INPUT);
|
||||||
|
String reversedNull = ReverseStringExamples.reverseUsingStringBuilder(null);
|
||||||
|
String reversedEmpty = ReverseStringExamples.reverseUsingStringBuilder(StringUtils.EMPTY);
|
||||||
|
|
||||||
|
assertEquals(STRING_INPUT_REVERSED, reversed);
|
||||||
|
assertEquals(null, reversedNull);
|
||||||
|
assertEquals(StringUtils.EMPTY, reversedEmpty);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenReverseUsingApacheCommonsIsCalled_ThenCorrectStringIsReturned() throws Exception {
|
||||||
|
String reversed = ReverseStringExamples.reverseUsingApacheCommons(STRING_INPUT);
|
||||||
|
String reversedNull = ReverseStringExamples.reverseUsingApacheCommons(null);
|
||||||
|
String reversedEmpty = ReverseStringExamples.reverseUsingApacheCommons(StringUtils.EMPTY);
|
||||||
|
|
||||||
|
assertEquals(STRING_INPUT_REVERSED, reversed);
|
||||||
|
assertEquals(null, reversedNull);
|
||||||
|
assertEquals(StringUtils.EMPTY, reversedEmpty);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenReverseTheOrderOfWordsIsCalled_ThenCorrectStringIsReturned() {
|
||||||
|
String reversed = ReverseStringExamples.reverseTheOrderOfWords(SENTENCE);
|
||||||
|
String reversedNull = ReverseStringExamples.reverseTheOrderOfWords(null);
|
||||||
|
String reversedEmpty = ReverseStringExamples.reverseTheOrderOfWords(StringUtils.EMPTY);
|
||||||
|
|
||||||
|
assertEquals(REVERSED_WORDS_SENTENCE, reversed);
|
||||||
|
assertEquals(null, reversedNull);
|
||||||
|
assertEquals(StringUtils.EMPTY, reversedEmpty);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenReverseTheOrderOfWordsUsingApacheCommonsIsCalled_ThenCorrectStringIsReturned() {
|
||||||
|
String reversed = ReverseStringExamples.reverseTheOrderOfWordsUsingApacheCommons(SENTENCE);
|
||||||
|
String reversedNull = ReverseStringExamples.reverseTheOrderOfWordsUsingApacheCommons(null);
|
||||||
|
String reversedEmpty = ReverseStringExamples.reverseTheOrderOfWordsUsingApacheCommons(StringUtils.EMPTY);
|
||||||
|
|
||||||
|
assertEquals(REVERSED_WORDS_SENTENCE, reversed);
|
||||||
|
assertEquals(null, reversedNull);
|
||||||
|
assertEquals(StringUtils.EMPTY, reversedEmpty);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -4,4 +4,4 @@
|
|||||||
- [A Guide to jBPM with Java](https://www.baeldung.com/jbpm-java)
|
- [A Guide to jBPM with Java](https://www.baeldung.com/jbpm-java)
|
||||||
- [Guide to Classgraph Library](https://www.baeldung.com/classgraph)
|
- [Guide to Classgraph Library](https://www.baeldung.com/classgraph)
|
||||||
- [Create a Java Command Line Program with Picocli](https://www.baeldung.com/java-picocli-create-command-line-program)
|
- [Create a Java Command Line Program with Picocli](https://www.baeldung.com/java-picocli-create-command-line-program)
|
||||||
|
- [Guide to Java Parallel Collectors Library](https://www.baeldung.com/java-parallel-collectors)
|
||||||
|
@ -2,17 +2,14 @@
|
|||||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
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">
|
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>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<artifactId>libraries2</artifactId>
|
<artifactId>libraries2</artifactId>
|
||||||
<name>libraries2</name>
|
<name>libraries2</name>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>parent-modules</artifactId>
|
<artifactId>parent-modules</artifactId>
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<repositories>
|
<repositories>
|
||||||
<repository>
|
<repository>
|
||||||
<id>jboss-public-repository-group</id>
|
<id>jboss-public-repository-group</id>
|
||||||
@ -28,8 +25,17 @@
|
|||||||
</snapshots>
|
</snapshots>
|
||||||
</repository>
|
</repository>
|
||||||
</repositories>
|
</repositories>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.mapdb</groupId>
|
||||||
|
<artifactId>mapdb</artifactId>
|
||||||
|
<version>${mapdb.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.pivovarit</groupId>
|
||||||
|
<artifactId>parallel-collectors</artifactId>
|
||||||
|
<version>1.1.0</version>
|
||||||
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.assertj</groupId>
|
<groupId>org.assertj</groupId>
|
||||||
<artifactId>assertj-core</artifactId>
|
<artifactId>assertj-core</artifactId>
|
||||||
@ -50,6 +56,26 @@
|
|||||||
<artifactId>picocli</artifactId>
|
<artifactId>picocli</artifactId>
|
||||||
<version>${picocli.version}</version>
|
<version>${picocli.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.ejml</groupId>
|
||||||
|
<artifactId>ejml-all</artifactId>
|
||||||
|
<version>${ejml.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.nd4j</groupId>
|
||||||
|
<artifactId>nd4j-native</artifactId>
|
||||||
|
<version>${nd4j.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.la4j</groupId>
|
||||||
|
<artifactId>la4j</artifactId>
|
||||||
|
<version>${la4j.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>colt</groupId>
|
||||||
|
<artifactId>colt</artifactId>
|
||||||
|
<version>${colt.version}</version>
|
||||||
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter</artifactId>
|
<artifactId>spring-boot-starter</artifactId>
|
||||||
@ -66,42 +92,57 @@
|
|||||||
</exclusion>
|
</exclusion>
|
||||||
</exclusions>
|
</exclusions>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- Dependencies for response decoder with okhttp -->
|
<!-- Dependencies for response decoder with okhttp -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.squareup.okhttp3</groupId>
|
<groupId>com.squareup.okhttp3</groupId>
|
||||||
<artifactId>okhttp</artifactId>
|
<artifactId>okhttp</artifactId>
|
||||||
<version>3.14.2</version>
|
<version>3.14.2</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.fasterxml.jackson.core</groupId>
|
<groupId>com.fasterxml.jackson.core</groupId>
|
||||||
<artifactId>jackson-databind</artifactId>
|
<artifactId>jackson-databind</artifactId>
|
||||||
<version>2.9.9</version>
|
<version>2.9.9</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.google.code.gson</groupId>
|
<groupId>com.google.code.gson</groupId>
|
||||||
<artifactId>gson</artifactId>
|
<artifactId>gson</artifactId>
|
||||||
<version>2.8.5</version>
|
<version>2.8.5</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.squareup.okhttp3</groupId>
|
<groupId>com.squareup.okhttp3</groupId>
|
||||||
<artifactId>mockwebserver</artifactId>
|
<artifactId>mockwebserver</artifactId>
|
||||||
<version>3.14.2</version>
|
<version>3.14.2</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>edu.uci.ics</groupId>
|
<groupId>edu.uci.ics</groupId>
|
||||||
<artifactId>crawler4j</artifactId>
|
<artifactId>crawler4j</artifactId>
|
||||||
<version>${crawler4j.version}</version>
|
<version>${crawler4j.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.github.jknack</groupId>
|
||||||
|
<artifactId>handlebars</artifactId>
|
||||||
|
<version>4.1.2</version>
|
||||||
|
</dependency>
|
||||||
|
<!-- Benchmarking -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.openjdk.jmh</groupId>
|
||||||
|
<artifactId>jmh-core</artifactId>
|
||||||
|
<version>${jmh.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.openjdk.jmh</groupId>
|
||||||
|
<artifactId>jmh-generator-annprocess</artifactId>
|
||||||
|
<version>${jmh.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.mesos</groupId>
|
||||||
|
<artifactId>mesos</artifactId>
|
||||||
|
<version>${mesos.library.version}</version>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
|
<mapdb.version>3.0.7</mapdb.version>
|
||||||
<assertj.version>3.6.2</assertj.version>
|
<assertj.version>3.6.2</assertj.version>
|
||||||
<classgraph.version>4.8.28</classgraph.version>
|
<classgraph.version>4.8.28</classgraph.version>
|
||||||
<jbpm.version>6.0.0.Final</jbpm.version>
|
<jbpm.version>6.0.0.Final</jbpm.version>
|
||||||
@ -109,5 +150,11 @@
|
|||||||
<chronicle.map.version>3.17.2</chronicle.map.version>
|
<chronicle.map.version>3.17.2</chronicle.map.version>
|
||||||
<crawler4j.version>4.4.0</crawler4j.version>
|
<crawler4j.version>4.4.0</crawler4j.version>
|
||||||
<spring-boot-starter.version>2.1.4.RELEASE</spring-boot-starter.version>
|
<spring-boot-starter.version>2.1.4.RELEASE</spring-boot-starter.version>
|
||||||
|
<ejml.version>0.38</ejml.version>
|
||||||
|
<nd4j.version>1.0.0-beta4</nd4j.version>
|
||||||
|
<colt.version>1.2.0</colt.version>
|
||||||
|
<la4j.version>0.6.0</la4j.version>
|
||||||
|
<jmh.version>1.19</jmh.version>
|
||||||
|
<mesos.library.version>0.28.3</mesos.library.version>
|
||||||
</properties>
|
</properties>
|
||||||
</project>
|
</project>
|
||||||
|
@ -0,0 +1,42 @@
|
|||||||
|
package com.baeldung.mesos;
|
||||||
|
|
||||||
|
import com.baeldung.mesos.schedulers.HelloWorldScheduler;
|
||||||
|
import org.apache.mesos.MesosSchedulerDriver;
|
||||||
|
import org.apache.mesos.Protos;
|
||||||
|
import org.apache.mesos.Protos.CommandInfo;
|
||||||
|
import org.apache.mesos.Protos.ExecutorInfo;
|
||||||
|
import org.apache.mesos.Protos.FrameworkInfo;
|
||||||
|
|
||||||
|
public class HelloWorldMain {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
|
||||||
|
String path = System.getProperty("user.dir")
|
||||||
|
+ "/target/libraries2-1.0.0-SNAPSHOT.jar";
|
||||||
|
|
||||||
|
CommandInfo.URI uri = CommandInfo.URI.newBuilder().setValue(path).setExtract(false).build();
|
||||||
|
|
||||||
|
String helloWorldCommand = "java -cp libraries2-1.0.0-SNAPSHOT.jar com.baeldung.mesos.executors.HelloWorldExecutor";
|
||||||
|
CommandInfo commandInfoHelloWorld = CommandInfo.newBuilder().setValue(helloWorldCommand).addUris(uri)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
ExecutorInfo executorHelloWorld = ExecutorInfo.newBuilder()
|
||||||
|
.setExecutorId(Protos.ExecutorID.newBuilder().setValue("HelloWorldExecutor"))
|
||||||
|
.setCommand(commandInfoHelloWorld).setName("Hello World (Java)").setSource("java").build();
|
||||||
|
|
||||||
|
FrameworkInfo.Builder frameworkBuilder = FrameworkInfo.newBuilder().setFailoverTimeout(120000)
|
||||||
|
.setUser("")
|
||||||
|
.setName("Hello World Framework (Java)");
|
||||||
|
|
||||||
|
frameworkBuilder.setPrincipal("test-framework-java");
|
||||||
|
|
||||||
|
MesosSchedulerDriver driver = new MesosSchedulerDriver(new HelloWorldScheduler(executorHelloWorld), frameworkBuilder.build(), args[0]);
|
||||||
|
|
||||||
|
int status = driver.run() == Protos.Status.DRIVER_STOPPED ? 0 : 1;
|
||||||
|
|
||||||
|
// Ensure that the driver process terminates.
|
||||||
|
driver.stop();
|
||||||
|
|
||||||
|
System.exit(status);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,59 @@
|
|||||||
|
package com.baeldung.mesos.executors;
|
||||||
|
|
||||||
|
import org.apache.mesos.Executor;
|
||||||
|
import org.apache.mesos.ExecutorDriver;
|
||||||
|
import org.apache.mesos.MesosExecutorDriver;
|
||||||
|
import org.apache.mesos.Protos;
|
||||||
|
import org.apache.mesos.Protos.TaskInfo;
|
||||||
|
|
||||||
|
public class HelloWorldExecutor implements Executor {
|
||||||
|
@Override
|
||||||
|
public void registered(ExecutorDriver driver, Protos.ExecutorInfo executorInfo, Protos.FrameworkInfo frameworkInfo, Protos.SlaveInfo slaveInfo) {
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void reregistered(ExecutorDriver driver, Protos.SlaveInfo slaveInfo) {
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void disconnected(ExecutorDriver driver) {
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void launchTask(ExecutorDriver driver, TaskInfo task) {
|
||||||
|
|
||||||
|
Protos.TaskStatus status = Protos.TaskStatus.newBuilder().setTaskId(task.getTaskId())
|
||||||
|
.setState(Protos.TaskState.TASK_RUNNING).build();
|
||||||
|
driver.sendStatusUpdate(status);
|
||||||
|
|
||||||
|
String myStatus = "Hello Framework";
|
||||||
|
driver.sendFrameworkMessage(myStatus.getBytes());
|
||||||
|
|
||||||
|
System.out.println("Hello World!!!");
|
||||||
|
|
||||||
|
status = Protos.TaskStatus.newBuilder().setTaskId(task.getTaskId())
|
||||||
|
.setState(Protos.TaskState.TASK_FINISHED).build();
|
||||||
|
driver.sendStatusUpdate(status);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void killTask(ExecutorDriver driver, Protos.TaskID taskId) {
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void frameworkMessage(ExecutorDriver driver, byte[] data) {
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void shutdown(ExecutorDriver driver) {
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void error(ExecutorDriver driver, String message) {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
MesosExecutorDriver driver = new MesosExecutorDriver(new HelloWorldExecutor());
|
||||||
|
System.exit(driver.run() == Protos.Status.DRIVER_STOPPED ? 0 : 1);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,100 @@
|
|||||||
|
package com.baeldung.mesos.schedulers;
|
||||||
|
|
||||||
|
import com.google.protobuf.ByteString;
|
||||||
|
import org.apache.mesos.Protos;
|
||||||
|
import org.apache.mesos.Protos.ExecutorInfo;
|
||||||
|
import org.apache.mesos.Protos.Offer;
|
||||||
|
import org.apache.mesos.Protos.OfferID;
|
||||||
|
import org.apache.mesos.Protos.TaskInfo;
|
||||||
|
import org.apache.mesos.Scheduler;
|
||||||
|
import org.apache.mesos.SchedulerDriver;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class HelloWorldScheduler implements Scheduler {
|
||||||
|
|
||||||
|
private int launchedTasks = 0;
|
||||||
|
private final ExecutorInfo helloWorldExecutor;
|
||||||
|
|
||||||
|
public HelloWorldScheduler(ExecutorInfo helloWorldExecutor) {
|
||||||
|
this.helloWorldExecutor = helloWorldExecutor;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void registered(SchedulerDriver schedulerDriver, Protos.FrameworkID frameworkID, Protos.MasterInfo masterInfo) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void reregistered(SchedulerDriver schedulerDriver, Protos.MasterInfo masterInfo) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void resourceOffers(SchedulerDriver schedulerDriver, List<Offer> list) {
|
||||||
|
|
||||||
|
for (Offer offer : list) {
|
||||||
|
List<TaskInfo> tasks = new ArrayList<TaskInfo>();
|
||||||
|
Protos.TaskID taskId = Protos.TaskID.newBuilder().setValue(Integer.toString(launchedTasks++)).build();
|
||||||
|
|
||||||
|
System.out.println("Launching printHelloWorld " + taskId.getValue() + " Hello World Java");
|
||||||
|
TaskInfo printHelloWorld = TaskInfo
|
||||||
|
.newBuilder()
|
||||||
|
.setName("printHelloWorld " + taskId.getValue())
|
||||||
|
.setTaskId(taskId)
|
||||||
|
.setSlaveId(offer.getSlaveId())
|
||||||
|
.addResources(
|
||||||
|
Protos.Resource.newBuilder().setName("cpus").setType(Protos.Value.Type.SCALAR)
|
||||||
|
.setScalar(Protos.Value.Scalar.newBuilder().setValue(1)))
|
||||||
|
.addResources(
|
||||||
|
Protos.Resource.newBuilder().setName("mem").setType(Protos.Value.Type.SCALAR)
|
||||||
|
.setScalar(Protos.Value.Scalar.newBuilder().setValue(128)))
|
||||||
|
.setExecutor(ExecutorInfo.newBuilder(helloWorldExecutor)).build();
|
||||||
|
|
||||||
|
List<OfferID> offerIDS = new ArrayList<>();
|
||||||
|
offerIDS.add(offer.getId());
|
||||||
|
|
||||||
|
tasks.add(printHelloWorld);
|
||||||
|
|
||||||
|
schedulerDriver.declineOffer(offer.getId());
|
||||||
|
schedulerDriver.launchTasks(offerIDS, tasks);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void offerRescinded(SchedulerDriver schedulerDriver, OfferID offerID) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void statusUpdate(SchedulerDriver schedulerDriver, Protos.TaskStatus taskStatus) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void frameworkMessage(SchedulerDriver schedulerDriver, Protos.ExecutorID executorID, Protos.SlaveID slaveID, byte[] bytes) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void disconnected(SchedulerDriver schedulerDriver) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void slaveLost(SchedulerDriver schedulerDriver, Protos.SlaveID slaveID) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void executorLost(SchedulerDriver schedulerDriver, Protos.ExecutorID executorID, Protos.SlaveID slaveID, int i) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void error(SchedulerDriver schedulerDriver, String s) {
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,109 @@
|
|||||||
|
package com.baeldung.handlebars;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import com.github.jknack.handlebars.Handlebars;
|
||||||
|
import com.github.jknack.handlebars.Template;
|
||||||
|
import com.github.jknack.handlebars.io.ClassPathTemplateLoader;
|
||||||
|
import com.github.jknack.handlebars.io.TemplateLoader;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Showcases the tag usage and different template loading mechanisms.
|
||||||
|
*
|
||||||
|
* @author isaolmez
|
||||||
|
*/
|
||||||
|
public class BasicUsageUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenThereIsNoTemplateFile_ThenCompilesInline() throws IOException {
|
||||||
|
Handlebars handlebars = new Handlebars();
|
||||||
|
Template template = handlebars.compileInline("Hi {{this}}!");
|
||||||
|
|
||||||
|
String templateString = template.apply("Baeldung");
|
||||||
|
|
||||||
|
assertThat(templateString).isEqualTo("Hi Baeldung!");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenParameterMapIsSupplied_thenDisplays() throws IOException {
|
||||||
|
Handlebars handlebars = new Handlebars();
|
||||||
|
Template template = handlebars.compileInline("Hi {{name}}!");
|
||||||
|
Map<String, String> parameterMap = new HashMap<>();
|
||||||
|
parameterMap.put("name", "Baeldung");
|
||||||
|
|
||||||
|
String templateString = template.apply(parameterMap);
|
||||||
|
|
||||||
|
assertThat(templateString).isEqualTo("Hi Baeldung!");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenParameterObjectIsSupplied_ThenDisplays() throws IOException {
|
||||||
|
Handlebars handlebars = new Handlebars();
|
||||||
|
Template template = handlebars.compileInline("Hi {{name}}!");
|
||||||
|
Person person = new Person();
|
||||||
|
person.setName("Baeldung");
|
||||||
|
|
||||||
|
String templateString = template.apply(person);
|
||||||
|
|
||||||
|
assertThat(templateString).isEqualTo("Hi Baeldung!");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenMultipleParametersAreSupplied_ThenDisplays() throws IOException {
|
||||||
|
Handlebars handlebars = new Handlebars();
|
||||||
|
Template template = handlebars.compileInline("Hi {{name}}! This is {{topic}}.");
|
||||||
|
Map<String, String> parameterMap = new HashMap<>();
|
||||||
|
parameterMap.put("name", "Baeldung");
|
||||||
|
parameterMap.put("topic", "Handlebars");
|
||||||
|
|
||||||
|
String templateString = template.apply(parameterMap);
|
||||||
|
|
||||||
|
assertThat(templateString).isEqualTo("Hi Baeldung! This is Handlebars.");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenNoLoaderIsGiven_ThenSearchesClasspath() throws IOException {
|
||||||
|
Handlebars handlebars = new Handlebars();
|
||||||
|
Template template = handlebars.compile("greeting");
|
||||||
|
Person person = getPerson("Baeldung");
|
||||||
|
|
||||||
|
String templateString = template.apply(person);
|
||||||
|
|
||||||
|
assertThat(templateString).isEqualTo("Hi Baeldung!");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenClasspathTemplateLoaderIsGiven_ThenSearchesClasspathWithPrefixSuffix() throws IOException {
|
||||||
|
TemplateLoader loader = new ClassPathTemplateLoader("/handlebars", ".html");
|
||||||
|
Handlebars handlebars = new Handlebars(loader);
|
||||||
|
Template template = handlebars.compile("greeting");
|
||||||
|
Person person = getPerson("Baeldung");
|
||||||
|
|
||||||
|
String templateString = template.apply(person);
|
||||||
|
|
||||||
|
assertThat(templateString).isEqualTo("Hi Baeldung!");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenMultipleLoadersAreGiven_ThenSearchesSequentially() throws IOException {
|
||||||
|
TemplateLoader firstLoader = new ClassPathTemplateLoader("/handlebars", ".html");
|
||||||
|
TemplateLoader secondLoader = new ClassPathTemplateLoader("/templates", ".html");
|
||||||
|
Handlebars handlebars = new Handlebars().with(firstLoader, secondLoader);
|
||||||
|
Template template = handlebars.compile("greeting");
|
||||||
|
Person person = getPerson("Baeldung");
|
||||||
|
|
||||||
|
String templateString = template.apply(person);
|
||||||
|
|
||||||
|
assertThat(templateString).isEqualTo("Hi Baeldung!");
|
||||||
|
}
|
||||||
|
|
||||||
|
private Person getPerson(String name) {
|
||||||
|
Person person = new Person();
|
||||||
|
person.setName(name);
|
||||||
|
return person;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,106 @@
|
|||||||
|
package com.baeldung.handlebars;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import com.github.jknack.handlebars.Handlebars;
|
||||||
|
import com.github.jknack.handlebars.Template;
|
||||||
|
import com.github.jknack.handlebars.io.ClassPathTemplateLoader;
|
||||||
|
import com.github.jknack.handlebars.io.TemplateLoader;
|
||||||
|
import java.io.IOException;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Showcases the built-in template helpers.
|
||||||
|
*
|
||||||
|
* @author isaolmez
|
||||||
|
*/
|
||||||
|
public class BuiltinHelperUnitTest {
|
||||||
|
|
||||||
|
private TemplateLoader templateLoader = new ClassPathTemplateLoader("/handlebars", ".html");
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsedWith_ThenContextChanges() throws IOException {
|
||||||
|
Handlebars handlebars = new Handlebars(templateLoader);
|
||||||
|
Template template = handlebars.compile("with");
|
||||||
|
Person person = getPerson("Baeldung");
|
||||||
|
person.getAddress().setStreet("World");
|
||||||
|
|
||||||
|
String templateString = template.apply(person);
|
||||||
|
|
||||||
|
assertThat(templateString).isEqualTo("\n<h4>I live in World</h4>\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsedWithMustacheStyle_ThenContextChanges() throws IOException {
|
||||||
|
Handlebars handlebars = new Handlebars(templateLoader);
|
||||||
|
Template template = handlebars.compile("with_mustache");
|
||||||
|
Person person = getPerson("Baeldung");
|
||||||
|
person.getAddress().setStreet("World");
|
||||||
|
|
||||||
|
String templateString = template.apply(person);
|
||||||
|
|
||||||
|
assertThat(templateString).isEqualTo("\n<h4>I live in World</h4>\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsedEach_ThenIterates() throws IOException {
|
||||||
|
Handlebars handlebars = new Handlebars(templateLoader);
|
||||||
|
Template template = handlebars.compile("each");
|
||||||
|
Person person = getPerson("Baeldung");
|
||||||
|
Person friend1 = getPerson("Java");
|
||||||
|
Person friend2 = getPerson("Spring");
|
||||||
|
person.getFriends().add(friend1);
|
||||||
|
person.getFriends().add(friend2);
|
||||||
|
|
||||||
|
String templateString = template.apply(person);
|
||||||
|
|
||||||
|
assertThat(templateString).isEqualTo("\n<span>Java is my friend.</span>\n"
|
||||||
|
+ "\n<span>Spring is my friend.</span>\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsedEachMustacheStyle_ThenIterates() throws IOException {
|
||||||
|
Handlebars handlebars = new Handlebars(templateLoader);
|
||||||
|
Template template = handlebars.compile("each_mustache");
|
||||||
|
Person person = getPerson("Baeldung");
|
||||||
|
Person friend1 = getPerson("Java");
|
||||||
|
Person friend2 = getPerson("Spring");
|
||||||
|
person.getFriends().add(friend1);
|
||||||
|
person.getFriends().add(friend2);
|
||||||
|
|
||||||
|
String templateString = template.apply(person);
|
||||||
|
|
||||||
|
assertThat(templateString).isEqualTo("\n<span>Java is my friend.</span>\n"
|
||||||
|
+ "\n<span>Spring is my friend.</span>\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsedIf_ThenPutsCondition() throws IOException {
|
||||||
|
Handlebars handlebars = new Handlebars(templateLoader);
|
||||||
|
Template template = handlebars.compile("if");
|
||||||
|
Person person = getPerson("Baeldung");
|
||||||
|
person.setBusy(true);
|
||||||
|
|
||||||
|
String templateString = template.apply(person);
|
||||||
|
|
||||||
|
assertThat(templateString).isEqualTo("\n<h4>Baeldung is busy.</h4>\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsedIfMustacheStyle_ThenPutsCondition() throws IOException {
|
||||||
|
Handlebars handlebars = new Handlebars(templateLoader);
|
||||||
|
Template template = handlebars.compile("if_mustache");
|
||||||
|
Person person = getPerson("Baeldung");
|
||||||
|
person.setBusy(true);
|
||||||
|
|
||||||
|
String templateString = template.apply(person);
|
||||||
|
|
||||||
|
assertThat(templateString).isEqualTo("\n<h4>Baeldung is busy.</h4>\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
private Person getPerson(String name) {
|
||||||
|
Person person = new Person();
|
||||||
|
person.setName(name);
|
||||||
|
return person;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,59 @@
|
|||||||
|
package com.baeldung.handlebars;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import com.github.jknack.handlebars.Handlebars;
|
||||||
|
import com.github.jknack.handlebars.Helper;
|
||||||
|
import com.github.jknack.handlebars.Options;
|
||||||
|
import com.github.jknack.handlebars.Template;
|
||||||
|
import com.github.jknack.handlebars.io.ClassPathTemplateLoader;
|
||||||
|
import com.github.jknack.handlebars.io.TemplateLoader;
|
||||||
|
import java.io.IOException;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Showcases implementing a custom template helper.
|
||||||
|
*
|
||||||
|
* @author isaolmez
|
||||||
|
*/
|
||||||
|
public class CustomHelperUnitTest {
|
||||||
|
|
||||||
|
private TemplateLoader templateLoader = new ClassPathTemplateLoader("/handlebars", ".html");
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenHelperIsCreated_ThenCanRegister() throws IOException {
|
||||||
|
Handlebars handlebars = new Handlebars(templateLoader);
|
||||||
|
handlebars.registerHelper("isBusy", new Helper<Person>() {
|
||||||
|
@Override
|
||||||
|
public Object apply(Person context, Options options) throws IOException {
|
||||||
|
String busyString = context.isBusy() ? "busy" : "available";
|
||||||
|
return context.getName() + " - " + busyString;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Template template = handlebars.compile("person");
|
||||||
|
Person person = getPerson("Baeldung");
|
||||||
|
|
||||||
|
String templateString = template.apply(person);
|
||||||
|
|
||||||
|
assertThat(templateString).isEqualTo("Baeldung - busy");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenHelperSourceIsCreated_ThenCanRegister() throws IOException {
|
||||||
|
Handlebars handlebars = new Handlebars(templateLoader);
|
||||||
|
handlebars.registerHelpers(new HelperSource());
|
||||||
|
Template template = handlebars.compile("person");
|
||||||
|
Person person = getPerson("Baeldung");
|
||||||
|
|
||||||
|
String templateString = template.apply(person);
|
||||||
|
|
||||||
|
assertThat(templateString).isEqualTo("Baeldung - busy");
|
||||||
|
}
|
||||||
|
|
||||||
|
private Person getPerson(String name) {
|
||||||
|
Person person = new Person();
|
||||||
|
person.setName(name);
|
||||||
|
person.setBusy(true);
|
||||||
|
return person;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,9 @@
|
|||||||
|
package com.baeldung.handlebars;
|
||||||
|
|
||||||
|
public class HelperSource {
|
||||||
|
|
||||||
|
public String isBusy(Person context) {
|
||||||
|
String busyString = context.isBusy() ? "busy" : "available";
|
||||||
|
return context.getName() + " - " + busyString;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,58 @@
|
|||||||
|
package com.baeldung.handlebars;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class Person {
|
||||||
|
|
||||||
|
private String name;
|
||||||
|
private boolean busy;
|
||||||
|
private Address address = new Address();
|
||||||
|
private List<Person> friends = new ArrayList<>();
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isBusy() {
|
||||||
|
return busy;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setBusy(boolean busy) {
|
||||||
|
this.busy = busy;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Address getAddress() {
|
||||||
|
return address;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setAddress(Address address) {
|
||||||
|
this.address = address;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Person> getFriends() {
|
||||||
|
return friends;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setFriends(List<Person> friends) {
|
||||||
|
this.friends = friends;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class Address {
|
||||||
|
|
||||||
|
private String street;
|
||||||
|
|
||||||
|
public String getStreet() {
|
||||||
|
return street;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setStreet(String street) {
|
||||||
|
this.street = street;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,49 @@
|
|||||||
|
package com.baeldung.handlebars;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import com.github.jknack.handlebars.Handlebars;
|
||||||
|
import com.github.jknack.handlebars.Template;
|
||||||
|
import com.github.jknack.handlebars.io.ClassPathTemplateLoader;
|
||||||
|
import com.github.jknack.handlebars.io.TemplateLoader;
|
||||||
|
import java.io.IOException;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Showcases reusing the existing templates.
|
||||||
|
*
|
||||||
|
* @author isaolmez
|
||||||
|
*/
|
||||||
|
public class ReusingTemplatesUnitTest {
|
||||||
|
|
||||||
|
private TemplateLoader templateLoader = new ClassPathTemplateLoader("/handlebars", ".html");
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenOtherTemplateIsReferenced_ThenCanReuse() throws IOException {
|
||||||
|
Handlebars handlebars = new Handlebars(templateLoader);
|
||||||
|
Template template = handlebars.compile("page");
|
||||||
|
Person person = new Person();
|
||||||
|
person.setName("Baeldung");
|
||||||
|
|
||||||
|
String templateString = template.apply(person);
|
||||||
|
|
||||||
|
assertThat(templateString).isEqualTo("<h4>Hi Baeldung!</h4>\n<p>This is the page Baeldung</p>");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenBlockIsDefined_ThenCanOverrideWithPartial() throws IOException {
|
||||||
|
Handlebars handlebars = new Handlebars(templateLoader);
|
||||||
|
Template template = handlebars.compile("simplemessage");
|
||||||
|
Person person = new Person();
|
||||||
|
person.setName("Baeldung");
|
||||||
|
|
||||||
|
String templateString = template.apply(person);
|
||||||
|
|
||||||
|
assertThat(templateString).isEqualTo("\n<html>\n"
|
||||||
|
+ "<body>\n"
|
||||||
|
+ "\n This is the intro\n\n"
|
||||||
|
+ "\n Hi there!\n\n"
|
||||||
|
+ "</body>\n"
|
||||||
|
+ "</html>");
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,33 @@
|
|||||||
|
package com.baeldung.mapdb;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.mapdb.DB;
|
||||||
|
import org.mapdb.DBMaker;
|
||||||
|
import org.mapdb.Serializer;
|
||||||
|
|
||||||
|
import java.util.NavigableSet;
|
||||||
|
|
||||||
|
import static junit.framework.Assert.assertEquals;
|
||||||
|
|
||||||
|
public class CollectionsUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSetCreatedInDB_whenMultipleElementsAdded_checkOnlyOneExists() {
|
||||||
|
|
||||||
|
DB db = DBMaker.memoryDB().make();
|
||||||
|
|
||||||
|
NavigableSet<String> set = db.
|
||||||
|
treeSet("mySet")
|
||||||
|
.serializer(Serializer.STRING)
|
||||||
|
.createOrOpen();
|
||||||
|
|
||||||
|
String myString = "Baeldung!";
|
||||||
|
|
||||||
|
set.add(myString);
|
||||||
|
set.add(myString);
|
||||||
|
|
||||||
|
assertEquals(1, set.size());
|
||||||
|
|
||||||
|
db.close();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,38 @@
|
|||||||
|
package com.baeldung.mapdb;
|
||||||
|
|
||||||
|
import org.jetbrains.annotations.NotNull;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.mapdb.*;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
import static junit.framework.Assert.assertEquals;
|
||||||
|
|
||||||
|
public class HTreeMapUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenValidDB_whenHTreeMapAddedToAndRetrieved_CheckedRetrievalCorrect() {
|
||||||
|
|
||||||
|
DB db = DBMaker.memoryDB().make();
|
||||||
|
|
||||||
|
HTreeMap<String, String> hTreeMap = db
|
||||||
|
.hashMap("myTreMap")
|
||||||
|
.keySerializer(Serializer.STRING)
|
||||||
|
.valueSerializer(Serializer.STRING)
|
||||||
|
.create();
|
||||||
|
|
||||||
|
hTreeMap.put("key1", "value1");
|
||||||
|
hTreeMap.put("key2", "value2");
|
||||||
|
|
||||||
|
assertEquals(2, hTreeMap.size());
|
||||||
|
|
||||||
|
//add another value with the same key
|
||||||
|
|
||||||
|
hTreeMap.put("key1", "value3");
|
||||||
|
|
||||||
|
assertEquals(2, hTreeMap.size());
|
||||||
|
assertEquals("value3", hTreeMap.get("key1"));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,49 @@
|
|||||||
|
package com.baeldung.mapdb;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.mapdb.DB;
|
||||||
|
import org.mapdb.DBMaker;
|
||||||
|
import org.mapdb.HTreeMap;
|
||||||
|
|
||||||
|
import java.util.concurrent.ConcurrentMap;
|
||||||
|
|
||||||
|
import static junit.framework.Assert.assertEquals;
|
||||||
|
|
||||||
|
public class HelloBaeldungUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenInMemoryDBInstantiateCorrectly_whenDataSavedAndRetrieved_checkRetrievalCorrect() {
|
||||||
|
|
||||||
|
DB db = DBMaker.memoryDB().make();
|
||||||
|
|
||||||
|
String welcomeMessageKey = "Welcome Message";
|
||||||
|
String welcomeMessageString = "Hello Baeldung!";
|
||||||
|
|
||||||
|
HTreeMap myMap = db.hashMap("myMap").createOrOpen();
|
||||||
|
myMap.put(welcomeMessageKey, welcomeMessageString);
|
||||||
|
|
||||||
|
String welcomeMessageFromDB = (String) myMap.get(welcomeMessageKey);
|
||||||
|
|
||||||
|
db.close();
|
||||||
|
|
||||||
|
assertEquals(welcomeMessageString, welcomeMessageFromDB);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenInFileDBInstantiateCorrectly_whenDataSavedAndRetrieved_checkRetrievalCorrect() {
|
||||||
|
|
||||||
|
DB db = DBMaker.fileDB("file.db").make();
|
||||||
|
|
||||||
|
String welcomeMessageKey = "Welcome Message";
|
||||||
|
String welcomeMessageString = "Hello Baeldung!";
|
||||||
|
|
||||||
|
HTreeMap myMap = db.hashMap("myMap").createOrOpen();
|
||||||
|
myMap.put(welcomeMessageKey, welcomeMessageString);
|
||||||
|
|
||||||
|
String welcomeMessageFromDB = (String) myMap.get(welcomeMessageKey);
|
||||||
|
|
||||||
|
db.close();
|
||||||
|
|
||||||
|
assertEquals(welcomeMessageString, welcomeMessageFromDB);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,62 @@
|
|||||||
|
package com.baeldung.mapdb;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.mapdb.DB;
|
||||||
|
import org.mapdb.DBMaker;
|
||||||
|
import org.mapdb.HTreeMap;
|
||||||
|
import org.mapdb.Serializer;
|
||||||
|
|
||||||
|
import static junit.framework.Assert.assertEquals;
|
||||||
|
|
||||||
|
public class InMemoryModesUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenDBCreatedOnHeap_whenUsed_checkUsageCorrect() {
|
||||||
|
|
||||||
|
DB heapDB = DBMaker.heapDB().make();
|
||||||
|
|
||||||
|
HTreeMap<Integer, String> map = heapDB
|
||||||
|
.hashMap("myMap")
|
||||||
|
.keySerializer(Serializer.INTEGER)
|
||||||
|
.valueSerializer(Serializer.STRING)
|
||||||
|
.createOrOpen();
|
||||||
|
|
||||||
|
map.put(1, "ONE");
|
||||||
|
|
||||||
|
assertEquals("ONE", map.get(1));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenDBCreatedBaseOnByteArray_whenUsed_checkUsageCorrect() {
|
||||||
|
|
||||||
|
DB heapDB = DBMaker.memoryDB().make();
|
||||||
|
|
||||||
|
HTreeMap<Integer, String> map = heapDB
|
||||||
|
.hashMap("myMap")
|
||||||
|
.keySerializer(Serializer.INTEGER)
|
||||||
|
.valueSerializer(Serializer.STRING)
|
||||||
|
.createOrOpen();
|
||||||
|
|
||||||
|
map.put(1, "ONE");
|
||||||
|
|
||||||
|
assertEquals("ONE", map.get(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenDBCreatedBaseOnDirectByteBuffer_whenUsed_checkUsageCorrect() {
|
||||||
|
|
||||||
|
DB heapDB = DBMaker.memoryDirectDB().make();
|
||||||
|
|
||||||
|
HTreeMap<Integer, String> map = heapDB
|
||||||
|
.hashMap("myMap")
|
||||||
|
.keySerializer(Serializer.INTEGER)
|
||||||
|
.valueSerializer(Serializer.STRING)
|
||||||
|
.createOrOpen();
|
||||||
|
|
||||||
|
map.put(1, "ONE");
|
||||||
|
|
||||||
|
assertEquals("ONE", map.get(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,47 @@
|
|||||||
|
package com.baeldung.mapdb;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.mapdb.Serializer;
|
||||||
|
import org.mapdb.SortedTableMap;
|
||||||
|
import org.mapdb.volume.MappedFileVol;
|
||||||
|
import org.mapdb.volume.Volume;
|
||||||
|
|
||||||
|
import static junit.framework.Assert.assertEquals;
|
||||||
|
|
||||||
|
public class SortedTableMapUnitTest {
|
||||||
|
|
||||||
|
private static final String VOLUME_LOCATION = "sortedTableMapVol.db";
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenValidSortedTableMapSetup_whenQueried_checkValuesCorrect() {
|
||||||
|
|
||||||
|
//create memory mapped volume, readonly false
|
||||||
|
Volume vol = MappedFileVol.FACTORY.makeVolume(VOLUME_LOCATION, false);
|
||||||
|
|
||||||
|
//create sink to feed the map with data
|
||||||
|
SortedTableMap.Sink<Integer, String> sink =
|
||||||
|
SortedTableMap.create(
|
||||||
|
vol,
|
||||||
|
Serializer.INTEGER,
|
||||||
|
Serializer.STRING
|
||||||
|
).createFromSink();
|
||||||
|
|
||||||
|
//add content
|
||||||
|
for(int i = 0; i < 100; i++){
|
||||||
|
sink.put(i, "Value " + Integer.toString(i));
|
||||||
|
}
|
||||||
|
|
||||||
|
sink.create();
|
||||||
|
|
||||||
|
//now open in read-only mode
|
||||||
|
Volume openVol = MappedFileVol.FACTORY.makeVolume(VOLUME_LOCATION, true);
|
||||||
|
|
||||||
|
SortedTableMap<Integer, String> sortedTableMap = SortedTableMap.open(
|
||||||
|
openVol,
|
||||||
|
Serializer.INTEGER,
|
||||||
|
Serializer.STRING
|
||||||
|
);
|
||||||
|
|
||||||
|
assertEquals(100, sortedTableMap.size());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,41 @@
|
|||||||
|
package com.baeldung.mapdb;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.mapdb.DB;
|
||||||
|
import org.mapdb.DBMaker;
|
||||||
|
import org.mapdb.Serializer;
|
||||||
|
|
||||||
|
import java.util.NavigableSet;
|
||||||
|
|
||||||
|
import static junit.framework.Assert.assertEquals;
|
||||||
|
|
||||||
|
public class TransactionsUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenValidDBSetup_whenTransactionCommittedAndRolledBack_checkPreviousStateAchieved() {
|
||||||
|
|
||||||
|
DB db = DBMaker.memoryDB().transactionEnable().make();
|
||||||
|
|
||||||
|
NavigableSet<String> set = db
|
||||||
|
.treeSet("mySet")
|
||||||
|
.serializer(Serializer.STRING)
|
||||||
|
.createOrOpen();
|
||||||
|
|
||||||
|
set.add("One");
|
||||||
|
set.add("Two");
|
||||||
|
|
||||||
|
db.commit();
|
||||||
|
|
||||||
|
assertEquals(2, set.size());
|
||||||
|
|
||||||
|
set.add("Three");
|
||||||
|
|
||||||
|
assertEquals(3, set.size());
|
||||||
|
|
||||||
|
db.rollback();
|
||||||
|
|
||||||
|
assertEquals(2, set.size());
|
||||||
|
|
||||||
|
db.close();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,9 @@
|
|||||||
|
package com.baeldung.matrices;
|
||||||
|
|
||||||
|
public class MatrixMultiplicationBenchmarking {
|
||||||
|
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
org.openjdk.jmh.Main.main(args);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,47 @@
|
|||||||
|
package com.baeldung.matrices.apache;
|
||||||
|
|
||||||
|
import org.apache.commons.math3.linear.Array2DRowRealMatrix;
|
||||||
|
import org.apache.commons.math3.linear.RealMatrix;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.openjdk.jmh.annotations.*;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
@BenchmarkMode(Mode.AverageTime)
|
||||||
|
@Fork(value = 2)
|
||||||
|
@Warmup(iterations = 5)
|
||||||
|
@Measurement(iterations = 10)
|
||||||
|
public class RealMatrixUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@Benchmark
|
||||||
|
public void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() {
|
||||||
|
RealMatrix firstMatrix = new Array2DRowRealMatrix(
|
||||||
|
new double[][] {
|
||||||
|
new double[] {1d, 5d},
|
||||||
|
new double[] {2d, 3d},
|
||||||
|
new double[] {1d ,7d}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
RealMatrix secondMatrix = new Array2DRowRealMatrix(
|
||||||
|
new double[][] {
|
||||||
|
new double[] {1d, 2d, 3d, 7d},
|
||||||
|
new double[] {5d, 2d, 8d, 1d}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
RealMatrix expected = new Array2DRowRealMatrix(
|
||||||
|
new double[][] {
|
||||||
|
new double[] {26d, 12d, 43d, 12d},
|
||||||
|
new double[] {17d, 10d, 30d, 17d},
|
||||||
|
new double[] {36d, 16d, 59d, 14d}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
RealMatrix actual = firstMatrix.multiply(secondMatrix);
|
||||||
|
|
||||||
|
assertThat(actual).isEqualTo(expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,51 @@
|
|||||||
|
package com.baeldung.matrices.colt;
|
||||||
|
|
||||||
|
import cern.colt.matrix.DoubleFactory2D;
|
||||||
|
import cern.colt.matrix.DoubleMatrix2D;
|
||||||
|
import cern.colt.matrix.linalg.Algebra;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.openjdk.jmh.annotations.*;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
@BenchmarkMode(Mode.AverageTime)
|
||||||
|
@Fork(value = 2)
|
||||||
|
@Warmup(iterations = 5)
|
||||||
|
@Measurement(iterations = 10)
|
||||||
|
public class DoubleMatrix2DUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@Benchmark
|
||||||
|
public void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() {
|
||||||
|
DoubleFactory2D doubleFactory2D = DoubleFactory2D.dense;
|
||||||
|
|
||||||
|
DoubleMatrix2D firstMatrix = doubleFactory2D.make(
|
||||||
|
new double[][] {
|
||||||
|
new double[] {1d, 5d},
|
||||||
|
new double[] {2d, 3d},
|
||||||
|
new double[] {1d ,7d}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
DoubleMatrix2D secondMatrix = doubleFactory2D.make(
|
||||||
|
new double[][] {
|
||||||
|
new double[] {1d, 2d, 3d, 7d},
|
||||||
|
new double[] {5d, 2d, 8d, 1d}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
DoubleMatrix2D expected = doubleFactory2D.make(
|
||||||
|
new double[][] {
|
||||||
|
new double[] {26d, 12d, 43d, 12d},
|
||||||
|
new double[] {17d, 10d, 30d, 17d},
|
||||||
|
new double[] {36d, 16d, 59d, 14d}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
Algebra algebra = new Algebra();
|
||||||
|
DoubleMatrix2D actual = algebra.mult(firstMatrix, secondMatrix);
|
||||||
|
|
||||||
|
assertThat(actual).isEqualTo(expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,46 @@
|
|||||||
|
package com.baeldung.matrices.ejml;
|
||||||
|
|
||||||
|
import org.ejml.simple.SimpleMatrix;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.openjdk.jmh.annotations.*;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
@BenchmarkMode(Mode.AverageTime)
|
||||||
|
@Fork(value = 2)
|
||||||
|
@Warmup(iterations = 5)
|
||||||
|
@Measurement(iterations = 10)
|
||||||
|
public class SimpleMatrixUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@Benchmark
|
||||||
|
public void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() {
|
||||||
|
SimpleMatrix firstMatrix = new SimpleMatrix(
|
||||||
|
new double[][] {
|
||||||
|
new double[] {1d, 5d},
|
||||||
|
new double[] {2d, 3d},
|
||||||
|
new double[] {1d ,7d}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
SimpleMatrix secondMatrix = new SimpleMatrix(
|
||||||
|
new double[][] {
|
||||||
|
new double[] {1d, 2d, 3d, 7d},
|
||||||
|
new double[] {5d, 2d, 8d, 1d}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
SimpleMatrix expected = new SimpleMatrix(
|
||||||
|
new double[][] {
|
||||||
|
new double[] {26d, 12d, 43d, 12d},
|
||||||
|
new double[] {17d, 10d, 30d, 17d},
|
||||||
|
new double[] {36d, 16d, 59d, 14d}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
SimpleMatrix actual = firstMatrix.mult(secondMatrix);
|
||||||
|
|
||||||
|
assertThat(actual).matches(m -> m.isIdentical(expected, 0d));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,58 @@
|
|||||||
|
package com.baeldung.matrices.homemade;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.openjdk.jmh.annotations.*;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
@BenchmarkMode(Mode.AverageTime)
|
||||||
|
@Fork(value = 2)
|
||||||
|
@Warmup(iterations = 5)
|
||||||
|
@Measurement(iterations = 10)
|
||||||
|
public class HomemadeMatrixUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@Benchmark
|
||||||
|
public void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() {
|
||||||
|
double[][] firstMatrix = {
|
||||||
|
new double[]{1d, 5d},
|
||||||
|
new double[]{2d, 3d},
|
||||||
|
new double[]{1d, 7d}
|
||||||
|
};
|
||||||
|
|
||||||
|
double[][] secondMatrix = {
|
||||||
|
new double[]{1d, 2d, 3d, 7d},
|
||||||
|
new double[]{5d, 2d, 8d, 1d}
|
||||||
|
};
|
||||||
|
|
||||||
|
double[][] expected = {
|
||||||
|
new double[]{26d, 12d, 43d, 12d},
|
||||||
|
new double[]{17d, 10d, 30d, 17d},
|
||||||
|
new double[]{36d, 16d, 59d, 14d}
|
||||||
|
};
|
||||||
|
|
||||||
|
double[][] actual = multiplyMatrices(firstMatrix, secondMatrix);
|
||||||
|
|
||||||
|
assertThat(actual).isEqualTo(expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
private double[][] multiplyMatrices(double[][] firstMatrix, double[][] secondMatrix) {
|
||||||
|
double[][] result = new double[firstMatrix.length][secondMatrix[0].length];
|
||||||
|
|
||||||
|
for (int row = 0; row < result.length; row++) {
|
||||||
|
for (int col = 0; col < result[row].length; col++) {
|
||||||
|
result[row][col] = multiplyMatricesCell(firstMatrix, secondMatrix, row, col);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private double multiplyMatricesCell(double[][] firstMatrix, double[][] secondMatrix, int row, int col) {
|
||||||
|
double cell = 0;
|
||||||
|
for (int i = 0; i < secondMatrix.length; i++) {
|
||||||
|
cell += firstMatrix[row][i] * secondMatrix[i][col];
|
||||||
|
}
|
||||||
|
return cell;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,47 @@
|
|||||||
|
package com.baeldung.matrices.la4j;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.la4j.Matrix;
|
||||||
|
import org.la4j.matrix.dense.Basic2DMatrix;
|
||||||
|
import org.openjdk.jmh.annotations.*;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
@BenchmarkMode(Mode.AverageTime)
|
||||||
|
@Fork(value = 2)
|
||||||
|
@Warmup(iterations = 5)
|
||||||
|
@Measurement(iterations = 10)
|
||||||
|
public class Basic2DMatrixUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@Benchmark
|
||||||
|
public void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() {
|
||||||
|
Matrix firstMatrix = new Basic2DMatrix(
|
||||||
|
new double[][]{
|
||||||
|
new double[]{1d, 5d},
|
||||||
|
new double[]{2d, 3d},
|
||||||
|
new double[]{1d, 7d}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
Matrix secondMatrix = new Basic2DMatrix(
|
||||||
|
new double[][]{
|
||||||
|
new double[]{1d, 2d, 3d, 7d},
|
||||||
|
new double[]{5d, 2d, 8d, 1d}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
Matrix expected = new Basic2DMatrix(
|
||||||
|
new double[][]{
|
||||||
|
new double[]{26d, 12d, 43d, 12d},
|
||||||
|
new double[]{17d, 10d, 30d, 17d},
|
||||||
|
new double[]{36d, 16d, 59d, 14d}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
Matrix actual = firstMatrix.multiply(secondMatrix);
|
||||||
|
|
||||||
|
assertThat(actual).isEqualTo(expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,46 @@
|
|||||||
|
package com.baeldung.matrices.nd4j;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.nd4j.linalg.api.ndarray.INDArray;
|
||||||
|
import org.nd4j.linalg.factory.Nd4j;
|
||||||
|
import org.openjdk.jmh.annotations.*;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
@BenchmarkMode(Mode.AverageTime)
|
||||||
|
@Fork(value = 2)
|
||||||
|
@Warmup(iterations = 5)
|
||||||
|
@Measurement(iterations = 10)
|
||||||
|
public class INDArrayUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() {
|
||||||
|
INDArray firstMatrix = Nd4j.create(
|
||||||
|
new double[][]{
|
||||||
|
new double[]{1d, 5d},
|
||||||
|
new double[]{2d, 3d},
|
||||||
|
new double[]{1d, 7d}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
INDArray secondMatrix = Nd4j.create(
|
||||||
|
new double[][] {
|
||||||
|
new double[] {1d, 2d, 3d, 7d},
|
||||||
|
new double[] {5d, 2d, 8d, 1d}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
INDArray expected = Nd4j.create(
|
||||||
|
new double[][] {
|
||||||
|
new double[] {26d, 12d, 43d, 12d},
|
||||||
|
new double[] {17d, 10d, 30d, 17d},
|
||||||
|
new double[] {36d, 16d, 59d, 14d}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
INDArray actual = firstMatrix.mmul(secondMatrix);
|
||||||
|
|
||||||
|
assertThat(actual).isEqualTo(expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,168 @@
|
|||||||
|
package com.baeldung.parallel_collectors;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.LinkedList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.TreeMap;
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.ThreadLocalRandom;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
import static com.pivovarit.collectors.ParallelCollectors.parallel;
|
||||||
|
import static com.pivovarit.collectors.ParallelCollectors.parallelOrdered;
|
||||||
|
import static com.pivovarit.collectors.ParallelCollectors.parallelToCollection;
|
||||||
|
import static com.pivovarit.collectors.ParallelCollectors.parallelToList;
|
||||||
|
import static com.pivovarit.collectors.ParallelCollectors.parallelToMap;
|
||||||
|
import static com.pivovarit.collectors.ParallelCollectors.parallelToStream;
|
||||||
|
|
||||||
|
public class ParallelCollectorsUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldProcessInParallelWithStreams() {
|
||||||
|
List<Integer> ids = Arrays.asList(1, 2, 3);
|
||||||
|
|
||||||
|
List<String> results = ids.parallelStream()
|
||||||
|
.map(i -> fetchById(i))
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
|
System.out.println(results);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldProcessInParallelWithParallelCollectors() {
|
||||||
|
ExecutorService executor = Executors.newFixedThreadPool(10);
|
||||||
|
|
||||||
|
List<Integer> ids = Arrays.asList(1, 2, 3);
|
||||||
|
|
||||||
|
CompletableFuture<List<String>> results = ids.stream()
|
||||||
|
.collect(parallelToList(i -> fetchById(i), executor, 4));
|
||||||
|
|
||||||
|
System.out.println(results.join());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldCollectToList() {
|
||||||
|
ExecutorService executor = Executors.newFixedThreadPool(10);
|
||||||
|
|
||||||
|
List<Integer> ids = Arrays.asList(1, 2, 3);
|
||||||
|
|
||||||
|
List<String> results = ids.stream()
|
||||||
|
.collect(parallelToList(i -> fetchById(i), executor, 4))
|
||||||
|
.join();
|
||||||
|
|
||||||
|
System.out.println(results); // [user-1, user-2, user-3]
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldCollectToCollection() {
|
||||||
|
ExecutorService executor = Executors.newFixedThreadPool(10);
|
||||||
|
|
||||||
|
List<Integer> ids = Arrays.asList(1, 2, 3);
|
||||||
|
|
||||||
|
List<String> results = ids.stream()
|
||||||
|
.collect(parallelToCollection(i -> fetchById(i), LinkedList::new, executor, 4))
|
||||||
|
.join();
|
||||||
|
|
||||||
|
System.out.println(results); // [user-1, user-2, user-3]
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldCollectToStream() {
|
||||||
|
ExecutorService executor = Executors.newFixedThreadPool(10);
|
||||||
|
|
||||||
|
List<Integer> ids = Arrays.asList(1, 2, 3);
|
||||||
|
|
||||||
|
Map<Integer, List<String>> results = ids.stream()
|
||||||
|
.collect(parallelToStream(i -> fetchById(i), executor, 4))
|
||||||
|
.thenApply(stream -> stream.collect(Collectors.groupingBy(i -> i.length())))
|
||||||
|
.join();
|
||||||
|
|
||||||
|
System.out.println(results); // [user-1, user-2, user-3]
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldStreamInCompletionOrder() {
|
||||||
|
ExecutorService executor = Executors.newFixedThreadPool(10);
|
||||||
|
|
||||||
|
List<Integer> ids = Arrays.asList(1, 2, 3);
|
||||||
|
|
||||||
|
ids.stream()
|
||||||
|
.collect(parallel(i -> fetchByIdWithRandomDelay(i), executor, 4))
|
||||||
|
.forEach(System.out::println);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldStreamInOriginalOrder() {
|
||||||
|
ExecutorService executor = Executors.newFixedThreadPool(10);
|
||||||
|
|
||||||
|
List<Integer> ids = Arrays.asList(1, 2, 3);
|
||||||
|
|
||||||
|
ids.stream()
|
||||||
|
.collect(parallelOrdered(i -> fetchByIdWithRandomDelay(i), executor, 4))
|
||||||
|
.forEach(System.out::println);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldCollectToMap() {
|
||||||
|
ExecutorService executor = Executors.newFixedThreadPool(10);
|
||||||
|
|
||||||
|
List<Integer> ids = Arrays.asList(1, 2, 3);
|
||||||
|
|
||||||
|
Map<Integer, String> results = ids.stream()
|
||||||
|
.collect(parallelToMap(i -> i, i -> fetchById(i), executor, 4))
|
||||||
|
.join();
|
||||||
|
|
||||||
|
System.out.println(results); // {1=user-1, 2=user-2, 3=user-3}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldCollectToTreeMap() {
|
||||||
|
ExecutorService executor = Executors.newFixedThreadPool(10);
|
||||||
|
|
||||||
|
List<Integer> ids = Arrays.asList(1, 2, 3);
|
||||||
|
|
||||||
|
Map<Integer, String> results = ids.stream()
|
||||||
|
.collect(parallelToMap(i -> i, i -> fetchById(i), TreeMap::new, executor, 4))
|
||||||
|
.join();
|
||||||
|
|
||||||
|
System.out.println(results); // {1=user-1, 2=user-2, 3=user-3}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldCollectToTreeMapAndResolveClashes() {
|
||||||
|
ExecutorService executor = Executors.newFixedThreadPool(10);
|
||||||
|
|
||||||
|
List<Integer> ids = Arrays.asList(1, 2, 3);
|
||||||
|
|
||||||
|
Map<Integer, String> results = ids.stream()
|
||||||
|
.collect(parallelToMap(i -> i, i -> fetchById(i), TreeMap::new, (s1, s2) -> s1, executor, 4))
|
||||||
|
.join();
|
||||||
|
|
||||||
|
System.out.println(results); // {1=user-1, 2=user-2, 3=user-3}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String fetchById(int id) {
|
||||||
|
try {
|
||||||
|
Thread.sleep(100);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
// ignore shamelessly
|
||||||
|
}
|
||||||
|
|
||||||
|
return "user-" + id;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String fetchByIdWithRandomDelay(int id) {
|
||||||
|
try {
|
||||||
|
Thread.sleep(ThreadLocalRandom.current().nextInt(1000));
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
// ignore shamelessly
|
||||||
|
}
|
||||||
|
|
||||||
|
return "user-" + id;
|
||||||
|
}
|
||||||
|
}
|
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