Merge branch 'master' of https://github.com/eugenp/tutorials
This commit is contained in:
commit
e5f9f601d1
|
@ -1,4 +1,5 @@
|
||||||
*/bin/*
|
*/bin/*
|
||||||
|
bin/
|
||||||
|
|
||||||
*.class
|
*.class
|
||||||
|
|
||||||
|
@ -21,6 +22,9 @@
|
||||||
*.iws
|
*.iws
|
||||||
out/
|
out/
|
||||||
|
|
||||||
|
# VSCode
|
||||||
|
.vscode/
|
||||||
|
|
||||||
# Mac
|
# Mac
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
|
||||||
|
@ -78,3 +82,4 @@ jta/transaction-logs/
|
||||||
software-security/sql-injection-samples/derby.log
|
software-security/sql-injection-samples/derby.log
|
||||||
spring-soap/src/main/java/com/baeldung/springsoap/gen/
|
spring-soap/src/main/java/com/baeldung/springsoap/gen/
|
||||||
/report-*.json
|
/report-*.json
|
||||||
|
transaction.log
|
|
@ -32,7 +32,7 @@ Running a Spring Boot module
|
||||||
====================
|
====================
|
||||||
To run a Spring Boot module run the command: `mvn spring-boot:run` in the module directory
|
To run a Spring Boot module run the command: `mvn spring-boot:run` in the module directory
|
||||||
|
|
||||||
#Running Tests
|
###Running Tests
|
||||||
|
|
||||||
The command `mvn clean install` will run the unit tests in a module.
|
The command `mvn clean install` will run the unit tests in a module.
|
||||||
To run the integration tests, use the command `mvn clean install -Pintegration-lite-first`
|
To run the integration tests, use the command `mvn clean install -Pintegration-lite-first`
|
||||||
|
|
|
@ -42,7 +42,7 @@
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.github.dpaukov</groupId>
|
<groupId>com.github.dpaukov</groupId>
|
||||||
<artifactId>combinatoricslib3</artifactId>
|
<artifactId>combinatoricslib3</artifactId>
|
||||||
<version>3.3.0</version>
|
<version>${combinatoricslib3.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
|
@ -83,6 +83,7 @@
|
||||||
<org.assertj.core.version>3.9.0</org.assertj.core.version>
|
<org.assertj.core.version>3.9.0</org.assertj.core.version>
|
||||||
<commons-codec.version>1.11</commons-codec.version>
|
<commons-codec.version>1.11</commons-codec.version>
|
||||||
<guava.version>27.0.1-jre</guava.version>
|
<guava.version>27.0.1-jre</guava.version>
|
||||||
|
<combinatoricslib3.version>3.3.0</combinatoricslib3.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
|
@ -4,3 +4,6 @@
|
||||||
- [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)
|
||||||
|
- [Checking if a Java Graph has a Cycle](https://www.baeldung.com/java-graph-has-a-cycle)
|
||||||
|
- [A Guide to the Folding Technique in Java](https://www.baeldung.com/folding-hashing-technique)
|
||||||
|
|
|
@ -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,51 @@
|
||||||
|
package com.baeldung.algorithms.graphcycledetection.domain;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class Graph {
|
||||||
|
|
||||||
|
private List<Vertex> vertices;
|
||||||
|
|
||||||
|
public Graph() {
|
||||||
|
this.vertices = new ArrayList<>();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Graph(List<Vertex> vertices) {
|
||||||
|
this.vertices = vertices;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void addVertex(Vertex vertex) {
|
||||||
|
this.vertices.add(vertex);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void addEdge(Vertex from, Vertex to) {
|
||||||
|
from.addNeighbour(to);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean hasCycle() {
|
||||||
|
for (Vertex vertex : vertices) {
|
||||||
|
if (!vertex.isVisited() && hasCycle(vertex)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean hasCycle(Vertex sourceVertex) {
|
||||||
|
sourceVertex.setBeingVisited(true);
|
||||||
|
|
||||||
|
for (Vertex neighbour : sourceVertex.getAdjacencyList()) {
|
||||||
|
if (neighbour.isBeingVisited()) {
|
||||||
|
// backward edge exists
|
||||||
|
return true;
|
||||||
|
} else if (!neighbour.isVisited() && hasCycle(neighbour)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sourceVertex.setBeingVisited(false);
|
||||||
|
sourceVertex.setVisited(true);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,56 @@
|
||||||
|
package com.baeldung.algorithms.graphcycledetection.domain;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class Vertex {
|
||||||
|
|
||||||
|
private String label;
|
||||||
|
|
||||||
|
private boolean visited;
|
||||||
|
|
||||||
|
private boolean beingVisited;
|
||||||
|
|
||||||
|
private List<Vertex> adjacencyList;
|
||||||
|
|
||||||
|
public Vertex(String label) {
|
||||||
|
this.label = label;
|
||||||
|
this.adjacencyList = new ArrayList<>();
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getLabel() {
|
||||||
|
return label;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setLabel(String label) {
|
||||||
|
this.label = label;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isVisited() {
|
||||||
|
return visited;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setVisited(boolean visited) {
|
||||||
|
this.visited = visited;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isBeingVisited() {
|
||||||
|
return beingVisited;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setBeingVisited(boolean beingVisited) {
|
||||||
|
this.beingVisited = beingVisited;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Vertex> getAdjacencyList() {
|
||||||
|
return adjacencyList;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setAdjacencyList(List<Vertex> adjacencyList) {
|
||||||
|
this.adjacencyList = adjacencyList;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void addNeighbour(Vertex adjacent) {
|
||||||
|
this.adjacencyList.add(adjacent);
|
||||||
|
}
|
||||||
|
}
|
|
@ -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,56 @@
|
||||||
|
package com.baeldung.algorithms.graphcycledetection;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.algorithms.graphcycledetection.domain.Graph;
|
||||||
|
import com.baeldung.algorithms.graphcycledetection.domain.Vertex;
|
||||||
|
|
||||||
|
public class GraphCycleDetectionUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenGraph_whenCycleExists_thenReturnTrue() {
|
||||||
|
|
||||||
|
Vertex vertexA = new Vertex("A");
|
||||||
|
Vertex vertexB = new Vertex("B");
|
||||||
|
Vertex vertexC = new Vertex("C");
|
||||||
|
Vertex vertexD = new Vertex("D");
|
||||||
|
|
||||||
|
Graph graph = new Graph();
|
||||||
|
graph.addVertex(vertexA);
|
||||||
|
graph.addVertex(vertexB);
|
||||||
|
graph.addVertex(vertexC);
|
||||||
|
graph.addVertex(vertexD);
|
||||||
|
|
||||||
|
graph.addEdge(vertexA, vertexB);
|
||||||
|
graph.addEdge(vertexB, vertexC);
|
||||||
|
graph.addEdge(vertexC, vertexA);
|
||||||
|
graph.addEdge(vertexD, vertexC);
|
||||||
|
|
||||||
|
assertTrue(graph.hasCycle());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenGraph_whenNoCycleExists_thenReturnFalse() {
|
||||||
|
|
||||||
|
Vertex vertexA = new Vertex("A");
|
||||||
|
Vertex vertexB = new Vertex("B");
|
||||||
|
Vertex vertexC = new Vertex("C");
|
||||||
|
Vertex vertexD = new Vertex("D");
|
||||||
|
|
||||||
|
Graph graph = new Graph();
|
||||||
|
graph.addVertex(vertexA);
|
||||||
|
graph.addVertex(vertexB);
|
||||||
|
graph.addVertex(vertexC);
|
||||||
|
graph.addVertex(vertexD);
|
||||||
|
|
||||||
|
graph.addEdge(vertexA, vertexB);
|
||||||
|
graph.addEdge(vertexB, vertexC);
|
||||||
|
graph.addEdge(vertexA, vertexC);
|
||||||
|
graph.addEdge(vertexD, vertexC);
|
||||||
|
|
||||||
|
assertFalse(graph.hasCycle());
|
||||||
|
}
|
||||||
|
}
|
|
@ -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);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -17,7 +17,7 @@
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>junit</groupId>
|
<groupId>junit</groupId>
|
||||||
<artifactId>junit</artifactId>
|
<artifactId>junit</artifactId>
|
||||||
<version>4.10</version>
|
<version>${junit.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
|
|
|
@ -3,37 +3,28 @@
|
||||||
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>
|
||||||
<parent>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-starter-parent</artifactId>
|
|
||||||
<version>2.1.3.RELEASE</version>
|
|
||||||
<relativePath /> <!-- lookup parent from repository -->
|
|
||||||
</parent>
|
|
||||||
<groupId>org.baeldung.examples.olingo2</groupId>
|
<groupId>org.baeldung.examples.olingo2</groupId>
|
||||||
<artifactId>olingo2-sample</artifactId>
|
<artifactId>olingo2-sample</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
<name>olingo2-sample</name>
|
<name>olingo2-sample</name>
|
||||||
<description>Sample Olingo 2 Project</description>
|
<description>Sample Olingo 2 Project</description>
|
||||||
|
|
||||||
<properties>
|
<parent>
|
||||||
<java.version>1.8</java.version>
|
<artifactId>parent-boot-2</artifactId>
|
||||||
<olingo2.version>2.0.11</olingo2.version>
|
<groupId>com.baeldung</groupId>
|
||||||
</properties>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
<relativePath>../../parent-boot-2</relativePath>
|
||||||
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter-jersey</artifactId>
|
<artifactId>spring-boot-starter-jersey</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.h2database</groupId>
|
<groupId>com.h2database</groupId>
|
||||||
<artifactId>h2</artifactId>
|
<artifactId>h2</artifactId>
|
||||||
|
@ -90,4 +81,8 @@
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<olingo2.version>2.0.11</olingo2.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
|
|
@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner;
|
||||||
|
|
||||||
@RunWith(SpringRunner.class)
|
@RunWith(SpringRunner.class)
|
||||||
@SpringBootTest
|
@SpringBootTest
|
||||||
public class Olingo2SampleApplicationTests {
|
public class Olingo2SampleApplicationUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void contextLoads() {
|
public void contextLoads() {
|
|
@ -7,6 +7,13 @@
|
||||||
<version>0.0.1</version>
|
<version>0.0.1</version>
|
||||||
<name>apache-pulsar</name>
|
<name>apache-pulsar</name>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>parent-modules</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
<relativePath>..</relativePath>
|
||||||
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.pulsar</groupId>
|
<groupId>org.apache.pulsar</groupId>
|
||||||
|
|
2
apache-pulsar/src/main/java/com/baeldung/ConsumerTest.java → apache-pulsar/src/main/java/com/baeldung/ConsumerUnitTest.java
Executable file → Normal file
2
apache-pulsar/src/main/java/com/baeldung/ConsumerTest.java → apache-pulsar/src/main/java/com/baeldung/ConsumerUnitTest.java
Executable file → Normal file
|
@ -7,7 +7,7 @@ import org.apache.pulsar.client.api.Message;
|
||||||
import org.apache.pulsar.client.api.PulsarClient;
|
import org.apache.pulsar.client.api.PulsarClient;
|
||||||
import org.apache.pulsar.client.api.SubscriptionType;
|
import org.apache.pulsar.client.api.SubscriptionType;
|
||||||
|
|
||||||
public class ConsumerTest {
|
public class ConsumerUnitTest {
|
||||||
|
|
||||||
private static final String SERVICE_URL = "pulsar://localhost:6650";
|
private static final String SERVICE_URL = "pulsar://localhost:6650";
|
||||||
private static final String TOPIC_NAME = "test-topic";
|
private static final String TOPIC_NAME = "test-topic";
|
2
apache-pulsar/src/main/java/com/baeldung/ProducerTest.java → apache-pulsar/src/main/java/com/baeldung/ProducerUnitTest.java
Executable file → Normal file
2
apache-pulsar/src/main/java/com/baeldung/ProducerTest.java → apache-pulsar/src/main/java/com/baeldung/ProducerUnitTest.java
Executable file → Normal file
|
@ -11,7 +11,7 @@ import org.apache.pulsar.client.api.PulsarClientException;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.stream.IntStream;
|
import java.util.stream.IntStream;
|
||||||
|
|
||||||
public class ProducerTest {
|
public class ProducerUnitTest {
|
||||||
|
|
||||||
private static final String SERVICE_URL = "pulsar://localhost:6650";
|
private static final String SERVICE_URL = "pulsar://localhost:6650";
|
||||||
private static final String TOPIC_NAME = "test-topic";
|
private static final String TOPIC_NAME = "test-topic";
|
|
@ -10,7 +10,7 @@ import org.apache.pulsar.client.api.SubscriptionType;
|
||||||
|
|
||||||
import java.util.stream.IntStream;
|
import java.util.stream.IntStream;
|
||||||
|
|
||||||
public class ExclusiveSubscriptionTest {
|
public class ExclusiveSubscriptionUnitTest {
|
||||||
private static final String SERVICE_URL = "pulsar://localhost:6650";
|
private static final String SERVICE_URL = "pulsar://localhost:6650";
|
||||||
private static final String TOPIC_NAME = "test-topic";
|
private static final String TOPIC_NAME = "test-topic";
|
||||||
private static final String SUBSCRIPTION_NAME = "test-subscription";
|
private static final String SUBSCRIPTION_NAME = "test-subscription";
|
|
@ -11,7 +11,7 @@ import org.apache.pulsar.client.api.SubscriptionType;
|
||||||
|
|
||||||
import java.util.stream.IntStream;
|
import java.util.stream.IntStream;
|
||||||
|
|
||||||
public class FailoverSubscriptionTest {
|
public class FailoverSubscriptionUnitTest {
|
||||||
private static final String SERVICE_URL = "pulsar://localhost:6650";
|
private static final String SERVICE_URL = "pulsar://localhost:6650";
|
||||||
private static final String TOPIC_NAME = "failover-subscription-test-topic";
|
private static final String TOPIC_NAME = "failover-subscription-test-topic";
|
||||||
private static final String SUBSCRIPTION_NAME = "test-subscription";
|
private static final String SUBSCRIPTION_NAME = "test-subscription";
|
|
@ -49,6 +49,7 @@
|
||||||
<version>${com.datastax.spark.spark-cassandra-connector-java.version}</version>
|
<version>${com.datastax.spark.spark-cassandra-connector-java.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
<plugins>
|
<plugins>
|
||||||
<plugin>
|
<plugin>
|
||||||
|
@ -78,6 +79,7 @@
|
||||||
</plugin>
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<org.apache.spark.spark-core.version>2.3.0</org.apache.spark.spark-core.version>
|
<org.apache.spark.spark-core.version>2.3.0</org.apache.spark.spark-core.version>
|
||||||
<org.apache.spark.spark-sql.version>2.3.0</org.apache.spark.spark-sql.version>
|
<org.apache.spark.spark-sql.version>2.3.0</org.apache.spark.spark-sql.version>
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
- [Introduction to AutoValue](http://www.baeldung.com/introduction-to-autovalue)
|
- [Introduction to AutoValue](http://www.baeldung.com/introduction-to-autovalue)
|
||||||
- [Introduction to AutoFactory](http://www.baeldung.com/autofactory)
|
- [Introduction to AutoFactory](http://www.baeldung.com/autofactory)
|
||||||
|
- [Google AutoService](https://www.baeldung.com/google-autoservice)
|
||||||
|
|
|
@ -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));
|
||||||
|
}
|
||||||
|
}
|
|
@ -112,7 +112,6 @@
|
||||||
</repositories>
|
</repositories>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<commons-io.version>2.5</commons-io.version>
|
|
||||||
<aws-lambda-java-events.version>1.3.0</aws-lambda-java-events.version>
|
<aws-lambda-java-events.version>1.3.0</aws-lambda-java-events.version>
|
||||||
<aws-lambda-java-core.version>1.1.0</aws-lambda-java-core.version>
|
<aws-lambda-java-core.version>1.1.0</aws-lambda-java-core.version>
|
||||||
<gson.version>2.8.0</gson.version>
|
<gson.version>2.8.0</gson.version>
|
||||||
|
|
|
@ -65,7 +65,6 @@
|
||||||
<properties>
|
<properties>
|
||||||
<main.class>com.baeldung.bootique.App</main.class>
|
<main.class>com.baeldung.bootique.App</main.class>
|
||||||
<bootique-bom.version>0.23</bootique-bom.version>
|
<bootique-bom.version>0.23</bootique-bom.version>
|
||||||
|
|
||||||
<maven-shade-plugin.version>2.4.3</maven-shade-plugin.version>
|
<maven-shade-plugin.version>2.4.3</maven-shade-plugin.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
|
|
|
@ -3,5 +3,8 @@
|
||||||
## Relevant articles:
|
## Relevant articles:
|
||||||
|
|
||||||
- [String Matching in Groovy](http://www.baeldung.com/)
|
- [String Matching in Groovy](http://www.baeldung.com/)
|
||||||
|
- [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)
|
||||||
|
- [Integrating Groovy into Java Applications](https://www.baeldung.com/groovy-java-applications)
|
||||||
|
|
|
@ -0,0 +1,178 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<artifactId>core-groovy-2</artifactId>
|
||||||
|
<version>1.0-SNAPSHOT</version>
|
||||||
|
<name>core-groovy-2</name>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>parent-modules</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.commons</groupId>
|
||||||
|
<artifactId>commons-lang3</artifactId>
|
||||||
|
<version>${commons-lang3.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>ch.qos.logback</groupId>
|
||||||
|
<artifactId>logback-classic</artifactId>
|
||||||
|
<version>${logback.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.codehaus.groovy</groupId>
|
||||||
|
<artifactId>groovy-all</artifactId>
|
||||||
|
<version>${groovy.version}</version>
|
||||||
|
<type>pom</type>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.platform</groupId>
|
||||||
|
<artifactId>junit-platform-runner</artifactId>
|
||||||
|
<version>${junit.platform.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.hsqldb</groupId>
|
||||||
|
<artifactId>hsqldb</artifactId>
|
||||||
|
<version>${hsqldb.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.spockframework</groupId>
|
||||||
|
<artifactId>spock-core</artifactId>
|
||||||
|
<version>${spock-core.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<scriptSourceDirectory>src/main/groovy</scriptSourceDirectory>
|
||||||
|
<sourceDirectory>src/main/java</sourceDirectory>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.codehaus.gmavenplus</groupId>
|
||||||
|
<artifactId>gmavenplus-plugin</artifactId>
|
||||||
|
<version>1.7.0</version>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<goals>
|
||||||
|
<goal>execute</goal>
|
||||||
|
<goal>addSources</goal>
|
||||||
|
<goal>addTestSources</goal>
|
||||||
|
<goal>generateStubs</goal>
|
||||||
|
<goal>compile</goal>
|
||||||
|
<goal>generateTestStubs</goal>
|
||||||
|
<goal>compileTests</goal>
|
||||||
|
<goal>removeStubs</goal>
|
||||||
|
<goal>removeTestStubs</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.codehaus.groovy</groupId>
|
||||||
|
<artifactId>groovy-all</artifactId>
|
||||||
|
<!-- any version of Groovy \>= 1.5.0 should work here -->
|
||||||
|
<version>${groovy.version}</version>
|
||||||
|
<scope>runtime</scope>
|
||||||
|
<type>pom</type>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<artifactId>maven-failsafe-plugin</artifactId>
|
||||||
|
<version>${maven-failsafe-plugin.version}</version>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.platform</groupId>
|
||||||
|
<artifactId>junit-platform-surefire-provider</artifactId>
|
||||||
|
<version>${junit.platform.version}</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<id>junit5</id>
|
||||||
|
<goals>
|
||||||
|
<goal>integration-test</goal>
|
||||||
|
<goal>verify</goal>
|
||||||
|
</goals>
|
||||||
|
<configuration>
|
||||||
|
<includes>
|
||||||
|
<include>**/*Test5.java</include>
|
||||||
|
</includes>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
|
<version>2.20.1</version>
|
||||||
|
<configuration>
|
||||||
|
<useFile>false</useFile>
|
||||||
|
<includes>
|
||||||
|
<include>**/*Test.java</include>
|
||||||
|
<include>**/*Spec.java</include>
|
||||||
|
</includes>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
<!-- Maven Assembly Plugin: needed to run the jar through command line -->
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-assembly-plugin</artifactId>
|
||||||
|
<version>3.1.0</version>
|
||||||
|
<configuration>
|
||||||
|
<!-- get all project dependencies -->
|
||||||
|
<descriptorRefs>
|
||||||
|
<descriptorRef>jar-with-dependencies</descriptorRef>
|
||||||
|
</descriptorRefs>
|
||||||
|
<!-- MainClass in mainfest make a executable jar -->
|
||||||
|
<archive>
|
||||||
|
<manifest>
|
||||||
|
<mainClass>com.baeldung.MyJointCompilationApp</mainClass>
|
||||||
|
</manifest>
|
||||||
|
</archive>
|
||||||
|
|
||||||
|
</configuration>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<id>make-assembly</id>
|
||||||
|
<!-- bind to the packaging phase -->
|
||||||
|
<phase>package</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>single</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<repositories>
|
||||||
|
<repository>
|
||||||
|
<id>central</id>
|
||||||
|
<url>http://jcenter.bintray.com</url>
|
||||||
|
</repository>
|
||||||
|
</repositories>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
|
<junit.platform.version>1.0.0</junit.platform.version>
|
||||||
|
<hsqldb.version>2.4.0</hsqldb.version>
|
||||||
|
<spock-core.version>1.1-groovy-2.4</spock-core.version>
|
||||||
|
<commons-lang3.version>3.9</commons-lang3.version>
|
||||||
|
<java.version>1.8</java.version>
|
||||||
|
<logback.version>1.2.3</logback.version>
|
||||||
|
<groovy.version>2.5.7</groovy.version>
|
||||||
|
<gmavenplus-plugin.version>1.6</gmavenplus-plugin.version>
|
||||||
|
</properties>
|
||||||
|
</project>
|
||||||
|
|
|
@ -15,25 +15,20 @@
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.codehaus.groovy</groupId>
|
<groupId>org.apache.commons</groupId>
|
||||||
<artifactId>groovy</artifactId>
|
<artifactId>commons-lang3</artifactId>
|
||||||
<version>${groovy.version}</version>
|
<version>${commons-lang3.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>ch.qos.logback</groupId>
|
||||||
|
<artifactId>logback-classic</artifactId>
|
||||||
|
<version>${logback.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.codehaus.groovy</groupId>
|
<groupId>org.codehaus.groovy</groupId>
|
||||||
<artifactId>groovy-all</artifactId>
|
<artifactId>groovy-all</artifactId>
|
||||||
<version>${groovy-all.version}</version>
|
|
||||||
<type>pom</type>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.codehaus.groovy</groupId>
|
|
||||||
<artifactId>groovy-dateutil</artifactId>
|
|
||||||
<version>${groovy.version}</version>
|
<version>${groovy.version}</version>
|
||||||
</dependency>
|
<type>pom</type>
|
||||||
<dependency>
|
|
||||||
<groupId>org.codehaus.groovy</groupId>
|
|
||||||
<artifactId>groovy-sql</artifactId>
|
|
||||||
<version>${groovy-sql.version}</version>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.junit.platform</groupId>
|
<groupId>org.junit.platform</groupId>
|
||||||
|
@ -56,21 +51,35 @@
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
|
<scriptSourceDirectory>src/main/groovy</scriptSourceDirectory>
|
||||||
|
<sourceDirectory>src/main/java</sourceDirectory>
|
||||||
<plugins>
|
<plugins>
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.codehaus.gmavenplus</groupId>
|
<groupId>org.codehaus.groovy</groupId>
|
||||||
<artifactId>gmavenplus-plugin</artifactId>
|
<artifactId>groovy-eclipse-compiler</artifactId>
|
||||||
<version>${gmavenplus-plugin.version}</version>
|
<version>3.3.0-01</version>
|
||||||
<executions>
|
<extensions>true</extensions>
|
||||||
<execution>
|
</plugin>
|
||||||
<goals>
|
<plugin>
|
||||||
<goal>addSources</goal>
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
<goal>addTestSources</goal>
|
<version>3.8.0</version>
|
||||||
<goal>compile</goal>
|
<configuration>
|
||||||
<goal>compileTests</goal>
|
<compilerId>groovy-eclipse-compiler</compilerId>
|
||||||
</goals>
|
<source>${java.version}</source>
|
||||||
</execution>
|
<target>${java.version}</target>
|
||||||
</executions>
|
</configuration>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.codehaus.groovy</groupId>
|
||||||
|
<artifactId>groovy-eclipse-compiler</artifactId>
|
||||||
|
<version>3.3.0-01</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.codehaus.groovy</groupId>
|
||||||
|
<artifactId>groovy-eclipse-batch</artifactId>
|
||||||
|
<version>${groovy.version}-01</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
</plugin>
|
</plugin>
|
||||||
<plugin>
|
<plugin>
|
||||||
<artifactId>maven-failsafe-plugin</artifactId>
|
<artifactId>maven-failsafe-plugin</artifactId>
|
||||||
|
@ -108,6 +117,35 @@
|
||||||
</includes>
|
</includes>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
<!-- Maven Assembly Plugin: needed to run the jar through command line -->
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-assembly-plugin</artifactId>
|
||||||
|
<version>3.1.0</version>
|
||||||
|
<configuration>
|
||||||
|
<!-- get all project dependencies -->
|
||||||
|
<descriptorRefs>
|
||||||
|
<descriptorRef>jar-with-dependencies</descriptorRef>
|
||||||
|
</descriptorRefs>
|
||||||
|
<!-- MainClass in mainfest make a executable jar -->
|
||||||
|
<archive>
|
||||||
|
<manifest>
|
||||||
|
<mainClass>com.baeldung.MyJointCompilationApp</mainClass>
|
||||||
|
</manifest>
|
||||||
|
</archive>
|
||||||
|
|
||||||
|
</configuration>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<id>make-assembly</id>
|
||||||
|
<!-- bind to the packaging phase -->
|
||||||
|
<phase>package</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>single</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
|
@ -118,14 +156,29 @@
|
||||||
</repository>
|
</repository>
|
||||||
</repositories>
|
</repositories>
|
||||||
|
|
||||||
|
<pluginRepositories>
|
||||||
|
<pluginRepository>
|
||||||
|
<id>bintray</id>
|
||||||
|
<name>Groovy Bintray</name>
|
||||||
|
<url>https://dl.bintray.com/groovy/maven</url>
|
||||||
|
<releases>
|
||||||
|
<!-- avoid automatic updates -->
|
||||||
|
<updatePolicy>never</updatePolicy>
|
||||||
|
</releases>
|
||||||
|
<snapshots>
|
||||||
|
<enabled>false</enabled>
|
||||||
|
</snapshots>
|
||||||
|
</pluginRepository>
|
||||||
|
</pluginRepositories>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<junit.platform.version>1.0.0</junit.platform.version>
|
<junit.platform.version>1.0.0</junit.platform.version>
|
||||||
<groovy.version>2.5.6</groovy.version>
|
|
||||||
<groovy-all.version>2.5.6</groovy-all.version>
|
|
||||||
<groovy-sql.version>2.5.6</groovy-sql.version>
|
|
||||||
<hsqldb.version>2.4.0</hsqldb.version>
|
<hsqldb.version>2.4.0</hsqldb.version>
|
||||||
<spock-core.version>1.1-groovy-2.4</spock-core.version>
|
<spock-core.version>1.1-groovy-2.4</spock-core.version>
|
||||||
<gmavenplus-plugin.version>1.6</gmavenplus-plugin.version>
|
<maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
|
||||||
|
<logback.version>1.2.3</logback.version>
|
||||||
|
<groovy.version>2.5.7</groovy.version>
|
||||||
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
</properties>
|
</properties>
|
||||||
</project>
|
</project>
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,25 @@
|
||||||
|
package com.baeldung
|
||||||
|
|
||||||
|
import org.slf4j.LoggerFactory
|
||||||
|
|
||||||
|
class CalcMath {
|
||||||
|
def log = LoggerFactory.getLogger(this.getClass())
|
||||||
|
|
||||||
|
def calcSum(x, y) {
|
||||||
|
log.info "Executing $x + $y"
|
||||||
|
x + y
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* example of method that in java would throw error at compile time
|
||||||
|
* @param x
|
||||||
|
* @param y
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
def calcSum2(x, y) {
|
||||||
|
log.info "Executing $x + $y"
|
||||||
|
// DANGER! This won't throw a compilation issue and fail only at runtime!!!
|
||||||
|
calcSum3()
|
||||||
|
log.info("Logging an undefined variable: $z")
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,16 @@
|
||||||
|
package com.baeldung
|
||||||
|
|
||||||
|
def calcSum(x, y) {
|
||||||
|
x + y
|
||||||
|
}
|
||||||
|
|
||||||
|
def calcSum2(x, y) {
|
||||||
|
// DANGER! The variable "log" may be undefined
|
||||||
|
log.info "Executing $x + $y"
|
||||||
|
// DANGER! This method doesn't exist!
|
||||||
|
calcSum3()
|
||||||
|
// DANGER! The logged variable "z" is undefined!
|
||||||
|
log.info("Logging an undefined variable: $z")
|
||||||
|
}
|
||||||
|
|
||||||
|
calcSum(1,5)
|
|
@ -0,0 +1,52 @@
|
||||||
|
package com.baeldung.concatenate
|
||||||
|
|
||||||
|
class Wonder {
|
||||||
|
|
||||||
|
String numOfWonder = 'seven'
|
||||||
|
|
||||||
|
String operator_plus() {
|
||||||
|
return 'The ' + numOfWonder + ' wonders of the world'
|
||||||
|
}
|
||||||
|
|
||||||
|
String operator_left() {
|
||||||
|
return 'The ' << numOfWonder << ' wonders of ' << 'the world'
|
||||||
|
}
|
||||||
|
|
||||||
|
String interpolation_one() {
|
||||||
|
return "The $numOfWonder wonders of the world"
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
String interpolation_two() {
|
||||||
|
return "The ${numOfWonder} wonders of the world"
|
||||||
|
}
|
||||||
|
|
||||||
|
String multilineString() {
|
||||||
|
return """
|
||||||
|
There are $numOfWonder wonders of the world.
|
||||||
|
Can you name them all?
|
||||||
|
1. The Great Pyramid of Giza
|
||||||
|
2. Hanging Gardens of Babylon
|
||||||
|
3. Colossus of Rhode
|
||||||
|
4. Lighthouse of Alexendra
|
||||||
|
5. Temple of Artemis
|
||||||
|
6. Status of Zeus at Olympia
|
||||||
|
7. Mausoleum at Halicarnassus
|
||||||
|
"""
|
||||||
|
}
|
||||||
|
|
||||||
|
String method_concat() {
|
||||||
|
return 'The '.concat(numOfWonder).concat(' wonders of the world')
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
String method_builder() {
|
||||||
|
return new StringBuilder()
|
||||||
|
.append('The ').append(numOfWonder).append(' wonders of the world')
|
||||||
|
}
|
||||||
|
|
||||||
|
String method_buffer() {
|
||||||
|
return new StringBuffer()
|
||||||
|
.append('The ').append(numOfWonder).append(' wonders of the world')
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,120 @@
|
||||||
|
package com.baeldung;
|
||||||
|
|
||||||
|
import groovy.lang.*;
|
||||||
|
import groovy.util.GroovyScriptEngine;
|
||||||
|
import groovy.util.ResourceException;
|
||||||
|
import groovy.util.ScriptException;
|
||||||
|
import org.codehaus.groovy.jsr223.GroovyScriptEngineFactory;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import javax.script.ScriptEngine;
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.FileNotFoundException;
|
||||||
|
import java.io.FileReader;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.MalformedURLException;
|
||||||
|
import java.net.URL;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hello world!
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
public class MyJointCompilationApp {
|
||||||
|
private final static Logger LOG = LoggerFactory.getLogger(MyJointCompilationApp.class);
|
||||||
|
private final GroovyClassLoader loader;
|
||||||
|
private final GroovyShell shell;
|
||||||
|
private final GroovyScriptEngine engine;
|
||||||
|
private final ScriptEngine engineFromFactory;
|
||||||
|
|
||||||
|
public MyJointCompilationApp() {
|
||||||
|
loader = new GroovyClassLoader(this.getClass().getClassLoader());
|
||||||
|
shell = new GroovyShell(loader, new Binding());
|
||||||
|
|
||||||
|
URL url = null;
|
||||||
|
try {
|
||||||
|
url = new File("src/main/groovy/com/baeldung/").toURI().toURL();
|
||||||
|
} catch (MalformedURLException e) {
|
||||||
|
LOG.error("Exception while creating url", e);
|
||||||
|
}
|
||||||
|
engine = new GroovyScriptEngine(new URL[] {url}, this.getClass().getClassLoader());
|
||||||
|
engineFromFactory = new GroovyScriptEngineFactory().getScriptEngine();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void addWithCompiledClasses(int x, int y) {
|
||||||
|
LOG.info("Executing {} + {}", x, y);
|
||||||
|
Object result1 = new CalcScript().calcSum(x, y);
|
||||||
|
LOG.info("Result of CalcScript.calcSum() method is {}", result1);
|
||||||
|
|
||||||
|
Object result2 = new CalcMath().calcSum(x, y);
|
||||||
|
LOG.info("Result of CalcMath.calcSum() method is {}", result2);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void addWithGroovyShell(int x, int y) throws IOException {
|
||||||
|
Script script = shell.parse(new File("src/main/groovy/com/baeldung/", "CalcScript.groovy"));
|
||||||
|
LOG.info("Executing {} + {}", x, y);
|
||||||
|
Object result = script.invokeMethod("calcSum", new Object[] { x, y });
|
||||||
|
LOG.info("Result of CalcScript.calcSum() method is {}", result);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void addWithGroovyShellRun() throws IOException {
|
||||||
|
Script script = shell.parse(new File("src/main/groovy/com/baeldung/", "CalcScript.groovy"));
|
||||||
|
LOG.info("Executing script run method");
|
||||||
|
Object result = script.run();
|
||||||
|
LOG.info("Result of CalcScript.run() method is {}", result);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void addWithGroovyClassLoader(int x, int y) throws IllegalAccessException, InstantiationException, IOException {
|
||||||
|
Class calcClass = loader.parseClass(
|
||||||
|
new File("src/main/groovy/com/baeldung/", "CalcMath.groovy"));
|
||||||
|
GroovyObject calc = (GroovyObject) calcClass.newInstance();
|
||||||
|
Object result = calc.invokeMethod("calcSum", new Object[] { x + 14, y + 14 });
|
||||||
|
LOG.info("Result of CalcMath.calcSum() method is {}", result);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void addWithGroovyScriptEngine(int x, int y) throws IllegalAccessException,
|
||||||
|
InstantiationException, ResourceException, ScriptException {
|
||||||
|
Class<GroovyObject> calcClass = engine.loadScriptByName("CalcMath.groovy");
|
||||||
|
GroovyObject calc = calcClass.newInstance();
|
||||||
|
//WARNING the following will throw a ClassCastException
|
||||||
|
//((CalcMath)calc).calcSum(1,2);
|
||||||
|
Object result = calc.invokeMethod("calcSum", new Object[] { x, y });
|
||||||
|
LOG.info("Result of CalcMath.calcSum() method is {}", result);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void addWithEngineFactory(int x, int y) throws IllegalAccessException,
|
||||||
|
InstantiationException, javax.script.ScriptException, FileNotFoundException {
|
||||||
|
Class calcClass = (Class) engineFromFactory.eval(
|
||||||
|
new FileReader(new File("src/main/groovy/com/baeldung/", "CalcMath.groovy")));
|
||||||
|
GroovyObject calc = (GroovyObject) calcClass.newInstance();
|
||||||
|
Object result = calc.invokeMethod("calcSum", new Object[] { x, y });
|
||||||
|
LOG.info("Result of CalcMath.calcSum() method is {}", result);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void addWithStaticCompiledClasses() {
|
||||||
|
LOG.info("Running the Groovy classes compiled statically...");
|
||||||
|
addWithCompiledClasses(5, 10);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private void addWithDynamicCompiledClasses() throws IOException, IllegalAccessException, InstantiationException,
|
||||||
|
ResourceException, ScriptException, javax.script.ScriptException {
|
||||||
|
LOG.info("Invocation of a dynamic groovy script...");
|
||||||
|
addWithGroovyShell(5, 10);
|
||||||
|
LOG.info("Invocation of the run method of a dynamic groovy script...");
|
||||||
|
addWithGroovyShellRun();
|
||||||
|
LOG.info("Invocation of a dynamic groovy class loaded with GroovyClassLoader...");
|
||||||
|
addWithGroovyClassLoader(10, 30);
|
||||||
|
LOG.info("Invocation of a dynamic groovy class loaded with GroovyScriptEngine...");
|
||||||
|
addWithGroovyScriptEngine(15, 0);
|
||||||
|
LOG.info("Invocation of a dynamic groovy class loaded with GroovyScriptEngine JSR223...");
|
||||||
|
addWithEngineFactory(5, 6);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) throws InstantiationException, IllegalAccessException,
|
||||||
|
ResourceException, ScriptException, IOException, javax.script.ScriptException {
|
||||||
|
MyJointCompilationApp myJointCompilationApp = new MyJointCompilationApp();
|
||||||
|
LOG.info("Example of addition operation via Groovy scripts integration with Java.");
|
||||||
|
myJointCompilationApp.addWithStaticCompiledClasses();
|
||||||
|
myJointCompilationApp.addWithDynamicCompiledClasses();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,69 @@
|
||||||
|
package com.baeldung.concatenate
|
||||||
|
|
||||||
|
import org.junit.Before
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
import static org.junit.Assert.*
|
||||||
|
|
||||||
|
class WonderUnitTest {
|
||||||
|
|
||||||
|
static final String EXPECTED_SINGLE_LINE = "The seven wonders of the world"
|
||||||
|
|
||||||
|
Wonder wonder
|
||||||
|
|
||||||
|
@Before
|
||||||
|
void before() {
|
||||||
|
wonder = new Wonder()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingOperatorPlus_thenConcatCorrectly() {
|
||||||
|
assertEquals(EXPECTED_SINGLE_LINE, wonder.operator_plus())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingOperatorLeft_thenConcatCorrectly() {
|
||||||
|
assertEquals(EXPECTED_SINGLE_LINE, wonder.operator_left())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingInterpolationOne_thenConcatCorrectly() {
|
||||||
|
assertEquals(EXPECTED_SINGLE_LINE, wonder.interpolation_one())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingInterpolationTwo_thenConcatCorrectly() {
|
||||||
|
assertEquals(EXPECTED_SINGLE_LINE, wonder.interpolation_two())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingMultiline_thenConcatCorrectly() {
|
||||||
|
def expectedMultiline = """
|
||||||
|
There are seven wonders of the world.
|
||||||
|
Can you name them all?
|
||||||
|
1. The Great Pyramid of Giza
|
||||||
|
2. Hanging Gardens of Babylon
|
||||||
|
3. Colossus of Rhode
|
||||||
|
4. Lighthouse of Alexendra
|
||||||
|
5. Temple of Artemis
|
||||||
|
6. Status of Zeus at Olympia
|
||||||
|
7. Mausoleum at Halicarnassus
|
||||||
|
"""
|
||||||
|
assertEquals(expectedMultiline, wonder.multilineString())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingMethodConcat_thenConcatCorrectly() {
|
||||||
|
assertEquals(EXPECTED_SINGLE_LINE, wonder.method_concat())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingMethodBuilder_thenConcatCorrectly() {
|
||||||
|
assertEquals(EXPECTED_SINGLE_LINE, wonder.method_builder())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingMethodBuffer_thenConcatCorrectly() {
|
||||||
|
assertEquals(EXPECTED_SINGLE_LINE, wonder.method_buffer())
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,45 @@
|
||||||
|
package com.baeldung.array.looping;
|
||||||
|
|
||||||
|
public class LoopDiagonally {
|
||||||
|
|
||||||
|
|
||||||
|
public String loopDiagonally(String[][] twoDArray) {
|
||||||
|
|
||||||
|
int length = twoDArray.length;
|
||||||
|
int diagonalLines = (length + length) - 1;
|
||||||
|
int itemsInDiagonal = 0;
|
||||||
|
int midPoint = (diagonalLines / 2) + 1;
|
||||||
|
StringBuilder output = new StringBuilder();
|
||||||
|
|
||||||
|
for (int i = 1; i <= diagonalLines; i++) {
|
||||||
|
|
||||||
|
StringBuilder items = new StringBuilder();
|
||||||
|
int rowIndex;
|
||||||
|
int columnIndex;
|
||||||
|
|
||||||
|
if (i <= midPoint) {
|
||||||
|
itemsInDiagonal++;
|
||||||
|
for (int j = 0; j < itemsInDiagonal; j++) {
|
||||||
|
rowIndex = (i - j) - 1;
|
||||||
|
columnIndex = j;
|
||||||
|
items.append(twoDArray[rowIndex][columnIndex]);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
itemsInDiagonal--;
|
||||||
|
for (int j = 0; j < itemsInDiagonal; j++) {
|
||||||
|
rowIndex = (length - 1) - j;
|
||||||
|
columnIndex = (i - length) + j;
|
||||||
|
items.append(twoDArray[rowIndex][columnIndex]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (i != diagonalLines) {
|
||||||
|
output.append(items).append(" ");
|
||||||
|
} else {
|
||||||
|
output.append(items);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return output.toString();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,20 @@
|
||||||
|
package com.baeldung.array.looping;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
public class LoopDiagonallyTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void twoArrayIsLoopedDiagonallyAsExpected() {
|
||||||
|
|
||||||
|
LoopDiagonally loopDiagonally = new LoopDiagonally();
|
||||||
|
String[][] twoDArray = {{"a", "b", "c"},
|
||||||
|
{"d", "e", "f"},
|
||||||
|
{"g", "h", "i"}};
|
||||||
|
|
||||||
|
String output = loopDiagonally.loopDiagonally(twoDArray);
|
||||||
|
assertEquals("a db gec hf i", output);
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,3 +1,6 @@
|
||||||
## Relevant articles:
|
## Relevant articles:
|
||||||
|
|
||||||
- [Multi-Module Maven Application with Java Modules](https://www.baeldung.com/maven-multi-module-project-java-jpms)
|
- [Multi-Module Maven Application with Java Modules](https://www.baeldung.com/maven-multi-module-project-java-jpms)
|
||||||
|
- [Guide to Java FileChannel](https://www.baeldung.com/java-filechannel)
|
||||||
|
- [Understanding the NumberFormatException in Java](https://www.baeldung.com/java-number-format-exception)
|
||||||
|
- [Will an Error Be Caught by Catch Block in Java?](https://www.baeldung.com/java-error-catch)
|
||||||
|
|
|
@ -5,3 +5,4 @@
|
||||||
- [Guide to Java 10](http://www.baeldung.com/java-10-overview)
|
- [Guide to Java 10](http://www.baeldung.com/java-10-overview)
|
||||||
- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)
|
- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)
|
||||||
- [Deep Dive Into the New Java JIT Compiler – Graal](https://www.baeldung.com/graal-java-jit-compiler)
|
- [Deep Dive Into the New Java JIT Compiler – Graal](https://www.baeldung.com/graal-java-jit-compiler)
|
||||||
|
- [Copying Sets in Java](https://www.baeldung.com/java-copy-sets)
|
||||||
|
|
|
@ -0,0 +1,13 @@
|
||||||
|
package com.baeldung.set;
|
||||||
|
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
public class CopySets {
|
||||||
|
|
||||||
|
// Using Java 10
|
||||||
|
public static <T> Set<T> copyBySetCopyOf(Set<T> original) {
|
||||||
|
Set<T> copy = Set.copyOf(original);
|
||||||
|
return copy;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -7,4 +7,5 @@
|
||||||
- [Exploring the New HTTP Client in Java 9 and 11](https://www.baeldung.com/java-9-http-client)
|
- [Exploring the New HTTP Client in Java 9 and 11](https://www.baeldung.com/java-9-http-client)
|
||||||
- [An Introduction to Epsilon GC: A No-Op Experimental Garbage Collector](https://www.baeldung.com/jvm-epsilon-gc-garbage-collector)
|
- [An Introduction to Epsilon GC: A No-Op Experimental Garbage Collector](https://www.baeldung.com/jvm-epsilon-gc-garbage-collector)
|
||||||
- [Guide to jlink](https://www.baeldung.com/jlink)
|
- [Guide to jlink](https://www.baeldung.com/jlink)
|
||||||
|
- [Negate a Predicate Method Reference with Java 11](https://www.baeldung.com/java-negate-predicate-method-reference)
|
||||||
- [Transforming an Empty String into an Empty Optional](https://www.baeldung.com/java-empty-string-to-empty-optional)
|
- [Transforming an Empty String into an Empty Optional](https://www.baeldung.com/java-empty-string-to-empty-optional)
|
||||||
|
|
|
@ -0,0 +1,3 @@
|
||||||
|
## Relevant articles:
|
||||||
|
|
||||||
|
- [Negate a Predicate Method Reference with Java 11](https://www.baeldung.com/java-negate-predicate-method-reference)
|
|
@ -0,0 +1,3 @@
|
||||||
|
## Relevant articles:
|
||||||
|
|
||||||
|
- [String API Updates in Java 12](https://www.baeldung.com/java12-string-api)
|
|
@ -3,5 +3,7 @@
|
||||||
## Core Java 8 Cookbooks and Examples (part 2)
|
## Core Java 8 Cookbooks and Examples (part 2)
|
||||||
|
|
||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
- [Anonymous Classes in Java](https://www.baeldung.com/java-anonymous-classes)
|
- [Anonymous Classes in Java](http://www.baeldung.com/)
|
||||||
|
- [How to Delay Code Execution in Java](https://www.baeldung.com/java-delay-code-execution)
|
||||||
- [Run JAR Application With Command Line Arguments](https://www.baeldung.com/java-run-jar-with-arguments)
|
- [Run JAR Application With Command Line Arguments](https://www.baeldung.com/java-run-jar-with-arguments)
|
||||||
|
- [Java 8 Stream skip() vs limit()](https://www.baeldung.com/java-stream-skip-vs-limit)
|
||||||
|
|
|
@ -9,7 +9,6 @@
|
||||||
<name>core-java-8-2</name>
|
<name>core-java-8-2</name>
|
||||||
<packaging>jar</packaging>
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>parent-java</artifactId>
|
<artifactId>parent-java</artifactId>
|
||||||
|
@ -17,16 +16,6 @@
|
||||||
<relativePath>../../parent-java</relativePath>
|
<relativePath>../../parent-java</relativePath>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<properties>
|
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
|
||||||
<maven.compiler.source>1.8</maven.compiler.source>
|
|
||||||
<maven.compiler.target>1.8</maven.compiler.target>
|
|
||||||
<icu.version>64.2</icu.version>
|
|
||||||
<hibernate.core.version>5.4.0.Final</hibernate.core.version>
|
|
||||||
<h2database.version>1.4.197</h2database.version>
|
|
||||||
<jackson.databind.version>2.9.8</jackson.databind.version>
|
|
||||||
</properties>
|
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.ibm.icu</groupId>
|
<groupId>com.ibm.icu</groupId>
|
||||||
|
@ -34,19 +23,10 @@
|
||||||
<version>${icu.version}</version>
|
<version>${icu.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.hibernate</groupId>
|
<groupId>org.assertj</groupId>
|
||||||
<artifactId>hibernate-core</artifactId>
|
<artifactId>assertj-core</artifactId>
|
||||||
<version>${hibernate.core.version}</version>
|
<version>${assertj.version}</version>
|
||||||
</dependency>
|
<scope>test</scope>
|
||||||
<dependency>
|
|
||||||
<groupId>com.h2database</groupId>
|
|
||||||
<artifactId>h2</artifactId>
|
|
||||||
<version>${h2database.version}</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.fasterxml.jackson.core</groupId>
|
|
||||||
<artifactId>jackson-databind</artifactId>
|
|
||||||
<version>${jackson.databind.version}</version>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
|
@ -62,6 +42,13 @@
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
|
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
|
<maven.compiler.source>1.8</maven.compiler.source>
|
||||||
|
<maven.compiler.target>1.8</maven.compiler.target>
|
||||||
|
<icu.version>64.2</icu.version>
|
||||||
|
<assertj.version>3.12.2</assertj.version>
|
||||||
|
</properties>
|
||||||
</project>
|
</project>
|
||||||
|
|
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
|
@ -40,3 +40,4 @@
|
||||||
- [Java 8 Predicate Chain](https://www.baeldung.com/java-predicate-chain)
|
- [Java 8 Predicate Chain](https://www.baeldung.com/java-predicate-chain)
|
||||||
- [Method References in Java](https://www.baeldung.com/java-method-references)
|
- [Method References in Java](https://www.baeldung.com/java-method-references)
|
||||||
- [Creating a Custom Annotation in Java](https://www.baeldung.com/java-custom-annotation)
|
- [Creating a Custom Annotation in Java](https://www.baeldung.com/java-custom-annotation)
|
||||||
|
- [The Difference Between Collection.stream().forEach() and Collection.forEach()](https://www.baeldung.com/java-collection-stream-foreach)
|
||||||
|
|
|
@ -175,7 +175,6 @@
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<!-- util -->
|
<!-- util -->
|
||||||
<commons-lang3.version>3.5</commons-lang3.version>
|
|
||||||
<commons-math3.version>3.6.1</commons-math3.version>
|
<commons-math3.version>3.6.1</commons-math3.version>
|
||||||
<commons-collections4.version>4.1</commons-collections4.version>
|
<commons-collections4.version>4.1</commons-collections4.version>
|
||||||
<collections-generic.version>4.01</collections-generic.version>
|
<collections-generic.version>4.01</collections-generic.version>
|
||||||
|
|
|
@ -0,0 +1,34 @@
|
||||||
|
package com.baeldung.java_8_features.groupingby;
|
||||||
|
|
||||||
|
public class Tuple {
|
||||||
|
|
||||||
|
private BlogPostType type;
|
||||||
|
private String author;
|
||||||
|
|
||||||
|
public Tuple(BlogPostType type, String author) {
|
||||||
|
super();
|
||||||
|
this.type = type;
|
||||||
|
this.author = author;
|
||||||
|
}
|
||||||
|
|
||||||
|
public BlogPostType getType() {
|
||||||
|
return type;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setType(BlogPostType type) {
|
||||||
|
this.type = type;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getAuthor() {
|
||||||
|
return author;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setAuthor(String author) {
|
||||||
|
this.author = author;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "Tuple [type=" + type + ", author=" + author + ", getType()=" + getType() + ", getAuthor()=" + getAuthor() + ", getClass()=" + getClass() + ", hashCode()=" + hashCode() + ", toString()=" + super.toString() + "]";
|
||||||
|
}
|
||||||
|
}
|
|
@ -259,4 +259,15 @@ public class OptionalUnitTest {
|
||||||
LOG.debug("Getting default value...");
|
LOG.debug("Getting default value...");
|
||||||
return "Default Value";
|
return "Default Value";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Uncomment code when code base is compatiable with Java 11
|
||||||
|
// @Test
|
||||||
|
// public void givenAnEmptyOptional_thenIsEmptyBehavesAsExpected() {
|
||||||
|
// Optional<String> opt = Optional.of("Baeldung");
|
||||||
|
// assertFalse(opt.isEmpty());
|
||||||
|
//
|
||||||
|
// opt = Optional.ofNullable(null);
|
||||||
|
// assertTrue(opt.isEmpty());
|
||||||
|
// }
|
||||||
|
|
||||||
}
|
}
|
|
@ -15,3 +15,4 @@
|
||||||
- [Intersection Between two Integer Arrays](https://www.baeldung.com/java-array-intersection)
|
- [Intersection Between two Integer Arrays](https://www.baeldung.com/java-array-intersection)
|
||||||
- [Sorting Arrays in Java](https://www.baeldung.com/java-sorting-arrays)
|
- [Sorting Arrays in Java](https://www.baeldung.com/java-sorting-arrays)
|
||||||
- [Convert a Float to a Byte Array in Java](https://www.baeldung.com/java-convert-float-to-byte-array)
|
- [Convert a Float to a Byte Array in Java](https://www.baeldung.com/java-convert-float-to-byte-array)
|
||||||
|
- [Converting Between Stream and Array in Java](https://www.baeldung.com/java-stream-to-array)
|
||||||
|
|
|
@ -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);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,71 @@
|
||||||
|
package com.baeldung.array;
|
||||||
|
|
||||||
|
import com.baeldung.arraycopy.model.Employee;
|
||||||
|
|
||||||
|
public class SortedArrayChecker {
|
||||||
|
boolean isSorted(int[] array, int length) {
|
||||||
|
if (array == null || length < 2)
|
||||||
|
return true;
|
||||||
|
|
||||||
|
if (array[length - 2] > array[length - 1])
|
||||||
|
return false;
|
||||||
|
|
||||||
|
return isSorted(array, length - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean isSorted(int[] array) {
|
||||||
|
for (int i = 0; i < array.length - 1; i++) {
|
||||||
|
if (array[i] > array[i + 1])
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean isSorted(String[] array, int length) {
|
||||||
|
if (array == null || length < 2)
|
||||||
|
return true;
|
||||||
|
|
||||||
|
if (array[length - 2].compareTo(array[length - 1]) > 0)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
return isSorted(array, length - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean isSorted(String[] array) {
|
||||||
|
for (int i = 0; i < array.length - 1; ++i) {
|
||||||
|
if (array[i].compareTo(array[i + 1]) > 0)
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean isSortedByName(Employee[] array) {
|
||||||
|
for (int i = 0; i < array.length - 1; ++i) {
|
||||||
|
if (array[i].getName().compareTo(array[i + 1].getName()) > 0)
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean isSortedByAge(Employee[] array) {
|
||||||
|
for (int i = 0; i < array.length - 1; ++i) {
|
||||||
|
if (array[i].getAge() > (array[i + 1].getAge()))
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean isSortedByAge(Employee[] array, int length) {
|
||||||
|
if (array == null || length < 2)
|
||||||
|
return true;
|
||||||
|
|
||||||
|
if (array[length - 2].getAge() > array[length - 1].getAge())
|
||||||
|
return false;
|
||||||
|
|
||||||
|
return isSortedByAge(array, length - 1);
|
||||||
|
}
|
||||||
|
}
|
|
@ -6,6 +6,7 @@ public class Employee implements Serializable {
|
||||||
private static final long serialVersionUID = -2454619097207585825L;
|
private static final long serialVersionUID = -2454619097207585825L;
|
||||||
private int id;
|
private int id;
|
||||||
private String name;
|
private String name;
|
||||||
|
private int age;
|
||||||
|
|
||||||
public Employee() {
|
public Employee() {
|
||||||
}
|
}
|
||||||
|
@ -15,10 +16,24 @@ public class Employee implements Serializable {
|
||||||
this.name = name;
|
this.name = name;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public Employee(int id, String name, int age) {
|
||||||
|
this.id = id;
|
||||||
|
this.name = name;
|
||||||
|
this.age = age;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getAge() {
|
||||||
|
return age;
|
||||||
|
}
|
||||||
|
|
||||||
public int getId() {
|
public int getId() {
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void setAge(int age) {
|
||||||
|
this.age = age;
|
||||||
|
}
|
||||||
|
|
||||||
public void setId(int id) {
|
public void setId(int id) {
|
||||||
this.id = id;
|
this.id = id;
|
||||||
}
|
}
|
||||||
|
|
|
@ -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));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,73 @@
|
||||||
|
package com.baeldung.array;
|
||||||
|
|
||||||
|
import com.baeldung.arraycopy.model.Employee;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
class SortedArrayCheckerUnitTest {
|
||||||
|
|
||||||
|
private static final int[] INTEGER_SORTED = {1, 3, 5, 7, 9};
|
||||||
|
private static final int[] INTEGER_NOT_SORTED = {1, 3, 11, 7};
|
||||||
|
|
||||||
|
private static final String[] STRING_SORTED = {"abc", "cde", "fgh"};
|
||||||
|
private static final String[] STRING_NOT_SORTED = {"abc", "fgh", "cde", "ijk"};
|
||||||
|
|
||||||
|
private final Employee[] EMPLOYEES_SORTED_BY_NAME = {
|
||||||
|
new Employee(1, "Carlos", 26),
|
||||||
|
new Employee(2, "Daniel", 31),
|
||||||
|
new Employee(3, "Marta", 27)};
|
||||||
|
|
||||||
|
private final Employee[] EMPLOYEES_NOT_SORTED_BY_NAME = {
|
||||||
|
new Employee(1, "Daniel", 31),
|
||||||
|
new Employee(2, "Carlos", 26),
|
||||||
|
new Employee(3, "Marta", 27)};
|
||||||
|
|
||||||
|
private final Employee[] EMPLOYEES_SORTED_BY_AGE = {
|
||||||
|
new Employee(1, "Carlos", 26),
|
||||||
|
new Employee(2, "Marta", 27),
|
||||||
|
new Employee(3, "Daniel", 31)};
|
||||||
|
|
||||||
|
private final Employee[] EMPLOYEES_NOT_SORTED_BY_AGE = {
|
||||||
|
new Employee(1, "Marta", 27),
|
||||||
|
new Employee(2, "Carlos", 26),
|
||||||
|
new Employee(3, "Daniel", 31)};
|
||||||
|
|
||||||
|
private SortedArrayChecker sortedArrayChecker;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setup() {
|
||||||
|
sortedArrayChecker = new SortedArrayChecker();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenIntegerArray_thenReturnIfItIsSortedOrNot() {
|
||||||
|
assertThat(sortedArrayChecker.isSorted(INTEGER_SORTED)).isEqualTo(true);
|
||||||
|
assertThat(sortedArrayChecker.isSorted(INTEGER_NOT_SORTED)).isEqualTo(false);
|
||||||
|
|
||||||
|
assertThat(sortedArrayChecker.isSorted(INTEGER_SORTED, INTEGER_SORTED.length)).isEqualTo(true);
|
||||||
|
assertThat(sortedArrayChecker.isSorted(INTEGER_NOT_SORTED, INTEGER_NOT_SORTED.length)).isEqualTo(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenStringArray_thenReturnIfItIsSortedOrNot() {
|
||||||
|
assertThat(sortedArrayChecker.isSorted(STRING_SORTED)).isEqualTo(true);
|
||||||
|
assertThat(sortedArrayChecker.isSorted(STRING_NOT_SORTED)).isEqualTo(false);
|
||||||
|
|
||||||
|
assertThat(sortedArrayChecker.isSorted(STRING_SORTED, STRING_SORTED.length)).isEqualTo(true);
|
||||||
|
assertThat(sortedArrayChecker.isSorted(STRING_NOT_SORTED, STRING_NOT_SORTED.length)).isEqualTo(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenEmployeeArray_thenReturnIfItIsSortedOrNot() {
|
||||||
|
assertThat(sortedArrayChecker.isSortedByName(EMPLOYEES_SORTED_BY_NAME)).isEqualTo(true);
|
||||||
|
assertThat(sortedArrayChecker.isSortedByName(EMPLOYEES_NOT_SORTED_BY_NAME)).isEqualTo(false);
|
||||||
|
|
||||||
|
assertThat(sortedArrayChecker.isSortedByAge(EMPLOYEES_SORTED_BY_AGE)).isEqualTo(true);
|
||||||
|
assertThat(sortedArrayChecker.isSortedByAge(EMPLOYEES_NOT_SORTED_BY_AGE)).isEqualTo(false);
|
||||||
|
|
||||||
|
assertThat(sortedArrayChecker.isSortedByAge(EMPLOYEES_SORTED_BY_AGE, EMPLOYEES_SORTED_BY_AGE.length)).isEqualTo(true);
|
||||||
|
assertThat(sortedArrayChecker.isSortedByAge(EMPLOYEES_NOT_SORTED_BY_AGE, EMPLOYEES_NOT_SORTED_BY_AGE.length)).isEqualTo(false);
|
||||||
|
}
|
||||||
|
}
|
|
@ -42,7 +42,7 @@ public class CoreJavaCollectionsUnitTest {
|
||||||
@Test(expected = UnsupportedOperationException.class)
|
@Test(expected = UnsupportedOperationException.class)
|
||||||
public final void givenUsingGuavaBuilder_whenUnmodifiableListIsCreatedFromOriginal_thenNoLongerModifiable() {
|
public final void givenUsingGuavaBuilder_whenUnmodifiableListIsCreatedFromOriginal_thenNoLongerModifiable() {
|
||||||
final List<String> list = new ArrayList<String>(Arrays.asList("one", "two", "three"));
|
final List<String> list = new ArrayList<String>(Arrays.asList("one", "two", "three"));
|
||||||
final ImmutableList<Object> unmodifiableList = ImmutableList.builder().addAll(list).build();
|
final ImmutableList<String> unmodifiableList = ImmutableList.<String>builder().addAll(list).build();
|
||||||
unmodifiableList.add("four");
|
unmodifiableList.add("four");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -10,3 +10,4 @@
|
||||||
- [Initializing HashSet at the Time of Construction](http://www.baeldung.com/java-initialize-hashset)
|
- [Initializing HashSet at the Time of Construction](http://www.baeldung.com/java-initialize-hashset)
|
||||||
- [Guide to EnumSet](https://www.baeldung.com/java-enumset)
|
- [Guide to EnumSet](https://www.baeldung.com/java-enumset)
|
||||||
- [Set Operations in Java](https://www.baeldung.com/java-set-operations)
|
- [Set Operations in Java](https://www.baeldung.com/java-set-operations)
|
||||||
|
- [Copying Sets in Java](https://www.baeldung.com/java-copy-sets)
|
||||||
|
|
|
@ -24,10 +24,21 @@
|
||||||
<artifactId>commons-collections4</artifactId>
|
<artifactId>commons-collections4</artifactId>
|
||||||
<version>${commons-collections4.version}</version>
|
<version>${commons-collections4.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.google.code.gson</groupId>
|
||||||
|
<artifactId>gson</artifactId>
|
||||||
|
<version>${gson.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>commons-lang</groupId>
|
||||||
|
<artifactId>commons-lang</artifactId>
|
||||||
|
<version>${commons-lang.version}</version>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<commons-collections4.version>4.3</commons-collections4.version>
|
<commons-collections4.version>4.3</commons-collections4.version>
|
||||||
<guava.version>27.1-jre</guava.version>
|
<guava.version>27.1-jre</guava.version>
|
||||||
|
<gson.version>2.8.5</gson.version>
|
||||||
</properties>
|
</properties>
|
||||||
</project>
|
</project>
|
|
@ -0,0 +1,59 @@
|
||||||
|
package com.baeldung.set;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
import org.apache.commons.lang.SerializationUtils;
|
||||||
|
|
||||||
|
import com.google.gson.Gson;
|
||||||
|
|
||||||
|
public class CopySets {
|
||||||
|
|
||||||
|
// Copy Constructor
|
||||||
|
public static <T> Set<T> copyByConstructor(Set<T> original) {
|
||||||
|
Set<T> copy = new HashSet<>(original);
|
||||||
|
return copy;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set.addAll
|
||||||
|
public static <T> Set<T> copyBySetAddAll(Set<T> original) {
|
||||||
|
Set<T> copy = new HashSet<>();
|
||||||
|
copy.addAll(original);
|
||||||
|
return copy;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set.clone
|
||||||
|
public static <T> Set<T> copyBySetClone(HashSet<T> original) {
|
||||||
|
Set<T> copy = (Set<T>) original.clone();
|
||||||
|
return copy;
|
||||||
|
}
|
||||||
|
|
||||||
|
// JSON
|
||||||
|
public static <T> Set<T> copyByJson(Set<T> original) {
|
||||||
|
Gson gson = new Gson();
|
||||||
|
String jsonStr = gson.toJson(original);
|
||||||
|
Set<T> copy = gson.fromJson(jsonStr, Set.class);
|
||||||
|
|
||||||
|
return copy;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apache Commons Lang
|
||||||
|
public static <T extends Serializable> Set<T> copyByApacheCommonsLang(Set<T> original) {
|
||||||
|
Set<T> copy = new HashSet<>();
|
||||||
|
for (T item : original) {
|
||||||
|
copy.add((T) SerializationUtils.clone(item));
|
||||||
|
}
|
||||||
|
return copy;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Collectors.toSet
|
||||||
|
public static <T extends Serializable> Set<T> copyByCollectorsToSet(Set<T> original) {
|
||||||
|
Set<T> copy = original.stream()
|
||||||
|
.collect(Collectors.toSet());
|
||||||
|
|
||||||
|
return copy;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -72,7 +72,6 @@
|
||||||
<properties>
|
<properties>
|
||||||
<!-- util -->
|
<!-- util -->
|
||||||
<guava.version>21.0</guava.version>
|
<guava.version>21.0</guava.version>
|
||||||
<commons-lang3.version>3.5</commons-lang3.version>
|
|
||||||
<commons-math3.version>3.6.1</commons-math3.version>
|
<commons-math3.version>3.6.1</commons-math3.version>
|
||||||
<commons-collections4.version>4.1</commons-collections4.version>
|
<commons-collections4.version>4.1</commons-collections4.version>
|
||||||
<collections-generic.version>4.01</collections-generic.version>
|
<collections-generic.version>4.01</collections-generic.version>
|
||||||
|
|
|
@ -17,3 +17,4 @@
|
||||||
- [Runnable vs. Callable in Java](http://www.baeldung.com/java-runnable-callable)
|
- [Runnable vs. Callable in Java](http://www.baeldung.com/java-runnable-callable)
|
||||||
- [What is Thread-Safety and How to Achieve it?](https://www.baeldung.com/java-thread-safety)
|
- [What is Thread-Safety and How to Achieve it?](https://www.baeldung.com/java-thread-safety)
|
||||||
- [How to Start a Thread in Java](https://www.baeldung.com/java-start-thread)
|
- [How to Start a Thread in Java](https://www.baeldung.com/java-start-thread)
|
||||||
|
- [How to Delay Code Execution in Java](https://www.baeldung.com/java-delay-code-execution)
|
||||||
|
|
|
@ -45,8 +45,6 @@
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<!-- util -->
|
|
||||||
<commons-lang3.version>3.5</commons-lang3.version>
|
|
||||||
<!-- testing -->
|
<!-- testing -->
|
||||||
<assertj.version>3.6.1</assertj.version>
|
<assertj.version>3.6.1</assertj.version>
|
||||||
<avaitility.version>1.7.0</avaitility.version>
|
<avaitility.version>1.7.0</avaitility.version>
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.delay;
|
package com.baeldung.concurrent.delay;
|
||||||
|
|
||||||
import java.util.concurrent.Executors;
|
import java.util.concurrent.Executors;
|
||||||
import java.util.concurrent.ScheduledExecutorService;
|
import java.util.concurrent.ScheduledExecutorService;
|
||||||
|
@ -61,6 +61,7 @@ public class Delay {
|
||||||
|
|
||||||
executorService.schedule(Delay::someTask1, delayInSeconds, TimeUnit.SECONDS);
|
executorService.schedule(Delay::someTask1, delayInSeconds, TimeUnit.SECONDS);
|
||||||
|
|
||||||
|
executorService.shutdown();
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void fixedRateServiceTask(Integer delayInSeconds) {
|
private static void fixedRateServiceTask(Integer delayInSeconds) {
|
||||||
|
@ -78,6 +79,7 @@ public class Delay {
|
||||||
|
|
||||||
sf.cancel(true);
|
sf.cancel(true);
|
||||||
|
|
||||||
|
executorService.shutdown();
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void someTask1() {
|
private static void someTask1() {
|
|
@ -62,7 +62,6 @@
|
||||||
<properties>
|
<properties>
|
||||||
<!-- util -->
|
<!-- util -->
|
||||||
<guava.version>21.0</guava.version>
|
<guava.version>21.0</guava.version>
|
||||||
<commons-lang3.version>3.5</commons-lang3.version>
|
|
||||||
<commons-math3.version>3.6.1</commons-math3.version>
|
<commons-math3.version>3.6.1</commons-math3.version>
|
||||||
<commons-collections4.version>4.1</commons-collections4.version>
|
<commons-collections4.version>4.1</commons-collections4.version>
|
||||||
<collections-generic.version>4.01</collections-generic.version>
|
<collections-generic.version>4.01</collections-generic.version>
|
||||||
|
|
|
@ -0,0 +1,3 @@
|
||||||
|
## Relevant articles:
|
||||||
|
|
||||||
|
- [Will an Error Be Caught by Catch Block in Java?](https://www.baeldung.com/java-error-catch)
|
|
@ -18,9 +18,18 @@
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>junit</groupId>
|
<groupId>junit</groupId>
|
||||||
<artifactId>junit</artifactId>
|
<artifactId>junit</artifactId>
|
||||||
<version>4.12</version>
|
<version>${junit.version}</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>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<commons-lang3.version>3.9</commons-lang3.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
</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 {
|
||||||
|
|
|
@ -248,7 +248,6 @@
|
||||||
<properties>
|
<properties>
|
||||||
|
|
||||||
<!-- util -->
|
<!-- util -->
|
||||||
<commons-lang3.version>3.5</commons-lang3.version>
|
|
||||||
<bouncycastle.version>1.55</bouncycastle.version>
|
<bouncycastle.version>1.55</bouncycastle.version>
|
||||||
<commons-codec.version>1.10</commons-codec.version>
|
<commons-codec.version>1.10</commons-codec.version>
|
||||||
<commons-math3.version>3.6.1</commons-math3.version>
|
<commons-math3.version>3.6.1</commons-math3.version>
|
||||||
|
|
|
@ -11,6 +11,14 @@
|
||||||
<version>1.0</version>
|
<version>1.0</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.baeldung.servicemodule</groupId>
|
||||||
|
<artifactId>servicemodule</artifactId>
|
||||||
|
<version>1.0</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
<plugins>
|
<plugins>
|
||||||
<plugin>
|
<plugin>
|
||||||
|
@ -19,12 +27,4 @@
|
||||||
</plugin>
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
<dependencies>
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.baeldung.servicemodule</groupId>
|
|
||||||
<artifactId>servicemodule</artifactId>
|
|
||||||
<version>1.0</version>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
|
||||||
</project>
|
</project>
|
||||||
|
|
|
@ -2,17 +2,18 @@
|
||||||
<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">
|
||||||
<parent>
|
|
||||||
<artifactId>com.baeldung.decoupling-pattern2</artifactId>
|
|
||||||
<groupId>decoupling-pattern2</groupId>
|
|
||||||
<version>1.0-SNAPSHOT</version>
|
|
||||||
</parent>
|
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
<groupId>com.baeldung.consumermodule</groupId>
|
<groupId>com.baeldung.consumermodule</groupId>
|
||||||
<artifactId>consumermodule</artifactId>
|
<artifactId>consumermodule</artifactId>
|
||||||
<version>1.0</version>
|
<version>1.0</version>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<artifactId>com.baeldung.decoupling-pattern2</artifactId>
|
||||||
|
<groupId>decoupling-pattern2</groupId>
|
||||||
|
<version>1.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.baeldung.servicemodule</groupId>
|
<groupId>com.baeldung.servicemodule</groupId>
|
||||||
|
|
|
@ -35,7 +35,6 @@
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<commons-lang3.version>3.5</commons-lang3.version>
|
|
||||||
<assertj.version>3.6.1</assertj.version>
|
<assertj.version>3.6.1</assertj.version>
|
||||||
</properties>
|
</properties>
|
||||||
</project>
|
</project>
|
||||||
|
|
|
@ -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)
|
|
|
@ -6,3 +6,4 @@
|
||||||
- [Generic Constructors in Java](https://www.baeldung.com/java-generic-constructors)
|
- [Generic Constructors in Java](https://www.baeldung.com/java-generic-constructors)
|
||||||
- [Cannot Reference “X” Before Supertype Constructor Has Been Called](https://www.baeldung.com/java-cannot-reference-x-before-supertype-constructor-error)
|
- [Cannot Reference “X” Before Supertype Constructor Has Been Called](https://www.baeldung.com/java-cannot-reference-x-before-supertype-constructor-error)
|
||||||
- [Anonymous Classes in Java](https://www.baeldung.com/java-anonymous-classes)
|
- [Anonymous Classes in Java](https://www.baeldung.com/java-anonymous-classes)
|
||||||
|
- [Raw Types in Java](https://www.baeldung.com/raw-types-java)
|
||||||
|
|
|
@ -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
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -75,13 +75,7 @@
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
|
|
||||||
<!-- marshalling -->
|
|
||||||
<jackson.version>2.8.5</jackson.version>
|
|
||||||
<gson.version>2.8.2</gson.version>
|
<gson.version>2.8.2</gson.version>
|
||||||
|
|
||||||
<!-- util -->
|
|
||||||
<commons-lang3.version>3.5</commons-lang3.version>
|
|
||||||
<!-- testing -->
|
<!-- testing -->
|
||||||
<assertj-core.version>3.10.0</assertj-core.version>
|
<assertj-core.version>3.10.0</assertj-core.version>
|
||||||
<equalsverifier.version>3.0.3</equalsverifier.version>
|
<equalsverifier.version>3.0.3</equalsverifier.version>
|
||||||
|
|
|
@ -54,3 +54,15 @@ class BankAccountCopyConstructor extends BankAccount {
|
||||||
this.balance = 0.0f;
|
this.balance = 0.0f;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
class BankAccountChainedConstructors extends BankAccount {
|
||||||
|
public BankAccountChainedConstructors(String name, LocalDateTime opened, double balance) {
|
||||||
|
this.name = name;
|
||||||
|
this.opened = opened;
|
||||||
|
this.balance = balance;
|
||||||
|
}
|
||||||
|
|
||||||
|
public BankAccountChainedConstructors(String name) {
|
||||||
|
this(name, LocalDateTime.now(), 0.0f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -1,15 +1,14 @@
|
||||||
package com.baeldung.constructors;
|
package com.baeldung.constructors;
|
||||||
|
|
||||||
import com.baeldung.constructors.*;
|
import com.google.common.collect.Comparators;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
import java.util.logging.Logger;
|
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.time.Month;
|
import java.time.Month;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
import org.junit.Test;
|
import static org.assertj.core.api.Assertions.*;
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
|
||||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
|
||||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
|
||||||
|
|
||||||
public class ConstructorUnitTest {
|
public class ConstructorUnitTest {
|
||||||
final static Logger LOGGER = Logger.getLogger(ConstructorUnitTest.class.getName());
|
final static Logger LOGGER = Logger.getLogger(ConstructorUnitTest.class.getName());
|
||||||
|
@ -17,7 +16,9 @@ public class ConstructorUnitTest {
|
||||||
@Test
|
@Test
|
||||||
public void givenNoExplicitContructor_whenUsed_thenFails() {
|
public void givenNoExplicitContructor_whenUsed_thenFails() {
|
||||||
BankAccount account = new BankAccount();
|
BankAccount account = new BankAccount();
|
||||||
assertThatThrownBy(() -> { account.toString(); }).isInstanceOf(Exception.class);
|
assertThatThrownBy(() -> {
|
||||||
|
account.toString();
|
||||||
|
}).isInstanceOf(Exception.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -50,4 +51,13 @@ public class ConstructorUnitTest {
|
||||||
|
|
||||||
assertThat(newAccount.getBalance()).isEqualTo(0.0f);
|
assertThat(newAccount.getBalance()).isEqualTo(0.0f);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenChainedConstructor_whenUsed_thenMaintainsLogic() {
|
||||||
|
BankAccountChainedConstructors account = new BankAccountChainedConstructors("Tim");
|
||||||
|
BankAccountChainedConstructors newAccount = new BankAccountChainedConstructors("Tim", LocalDateTime.now(), 0.0f);
|
||||||
|
|
||||||
|
assertThat(account.getName()).isEqualTo(newAccount.getName());
|
||||||
|
assertThat(account.getBalance()).isEqualTo(newAccount.getBalance());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -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());
|
||||||
|
}
|
||||||
|
}
|
|
@ -18,7 +18,6 @@
|
||||||
- [A Guide to Inner Interfaces in Java](http://www.baeldung.com/java-inner-interfaces)
|
- [A Guide to Inner Interfaces in Java](http://www.baeldung.com/java-inner-interfaces)
|
||||||
- [Recursion In Java](http://www.baeldung.com/java-recursion)
|
- [Recursion In Java](http://www.baeldung.com/java-recursion)
|
||||||
- [A Guide to the finalize Method in Java](http://www.baeldung.com/java-finalize)
|
- [A Guide to the finalize Method in Java](http://www.baeldung.com/java-finalize)
|
||||||
- [A Guide to Java Enums](http://www.baeldung.com/a-guide-to-java-enums)
|
|
||||||
- [Infinite Loops in Java](http://www.baeldung.com/infinite-loops-java)
|
- [Infinite Loops in Java](http://www.baeldung.com/infinite-loops-java)
|
||||||
- [Quick Guide to java.lang.System](http://www.baeldung.com/java-lang-system)
|
- [Quick Guide to java.lang.System](http://www.baeldung.com/java-lang-system)
|
||||||
- [Using Java Assertions](http://www.baeldung.com/java-assert)
|
- [Using Java Assertions](http://www.baeldung.com/java-assert)
|
||||||
|
|
|
@ -76,9 +76,6 @@
|
||||||
<properties>
|
<properties>
|
||||||
<gson.version>2.8.2</gson.version>
|
<gson.version>2.8.2</gson.version>
|
||||||
|
|
||||||
<!-- util -->
|
|
||||||
<commons-lang3.version>3.5</commons-lang3.version>
|
|
||||||
|
|
||||||
<javax.mail.version>1.5.0-b01</javax.mail.version>
|
<javax.mail.version>1.5.0-b01</javax.mail.version>
|
||||||
|
|
||||||
<!-- testing -->
|
<!-- testing -->
|
||||||
|
|
|
@ -42,8 +42,6 @@
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<javax.mail.version>1.5.0-b01</javax.mail.version>
|
<javax.mail.version>1.5.0-b01</javax.mail.version>
|
||||||
<commons-io.version>2.5</commons-io.version>
|
|
||||||
<commons-lang3.version>3.5</commons-lang3.version>
|
|
||||||
<springframework.spring-web.version>4.3.4.RELEASE</springframework.spring-web.version>
|
<springframework.spring-web.version>4.3.4.RELEASE</springframework.spring-web.version>
|
||||||
</properties>
|
</properties>
|
||||||
</project>
|
</project>
|
||||||
|
|
|
@ -0,0 +1,3 @@
|
||||||
|
## Relevant articles:
|
||||||
|
|
||||||
|
- [Determine File Creating Date in Java](https://www.baeldung.com/java-file-creation-date)
|
|
@ -0,0 +1,35 @@
|
||||||
|
package com.baeldung.creationdate;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.attribute.BasicFileAttributes;
|
||||||
|
import java.nio.file.attribute.FileTime;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
public class CreationDateResolver {
|
||||||
|
|
||||||
|
public Instant resolveCreationTimeWithBasicAttributes(Path path) {
|
||||||
|
try {
|
||||||
|
final BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class);
|
||||||
|
final FileTime fileTime = attr.creationTime();
|
||||||
|
|
||||||
|
return fileTime.toInstant();
|
||||||
|
} catch (IOException ex) {
|
||||||
|
throw new RuntimeException("An issue occured went wrong when resolving creation time", ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public Optional<Instant> resolveCreationTimeWithAttribute(Path path) {
|
||||||
|
try {
|
||||||
|
final FileTime creationTime = (FileTime) Files.getAttribute(path, "creationTime");
|
||||||
|
|
||||||
|
return Optional
|
||||||
|
.ofNullable(creationTime)
|
||||||
|
.map((FileTime::toInstant));
|
||||||
|
} catch (IOException ex) {
|
||||||
|
throw new RuntimeException("An issue occured went wrong when resolving creation time", ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,45 @@
|
||||||
|
package com.baeldung.creationdate;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
public class CreationDateResolverUnitTest {
|
||||||
|
|
||||||
|
private final CreationDateResolver creationDateResolver = new CreationDateResolver();
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenFile_whenGettingCreationDateTimeFromBasicAttributes_thenReturnDate() throws Exception {
|
||||||
|
|
||||||
|
final File file = File.createTempFile("createdFile", ".txt");
|
||||||
|
final Path path = file.toPath();
|
||||||
|
|
||||||
|
final Instant response = creationDateResolver.resolveCreationTimeWithBasicAttributes(path);
|
||||||
|
|
||||||
|
assertTrue(Instant
|
||||||
|
.now()
|
||||||
|
.isAfter(response));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenFile_whenGettingCreationDateTimeFromAttribute_thenReturnDate() throws Exception {
|
||||||
|
|
||||||
|
final File file = File.createTempFile("createdFile", ".txt");
|
||||||
|
final Path path = file.toPath();
|
||||||
|
|
||||||
|
final Optional<Instant> response = creationDateResolver.resolveCreationTimeWithAttribute(path);
|
||||||
|
|
||||||
|
response.ifPresent((value) -> {
|
||||||
|
assertTrue(Instant
|
||||||
|
.now()
|
||||||
|
.isAfter(value));
|
||||||
|
});
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,6 @@
|
||||||
|
=========
|
||||||
|
|
||||||
|
## Core Java Optional
|
||||||
|
|
||||||
|
### Relevant Articles:
|
||||||
|
- [Java Optional as Return Type](https://www.baeldung.com/java-optional-return)
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue