commit
8470319d13
5
.gitignore
vendored
5
.gitignore
vendored
@ -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
|
25
README.md
25
README.md
@ -1,12 +1,16 @@
|
|||||||
|
|
||||||
The "REST with Spring" Classes
|
The Courses
|
||||||
==============================
|
==============================
|
||||||
|
|
||||||
Here's the Master Class of REST With Spring (along with the newly announced Boot 2 material): <br/>
|
|
||||||
**[>> THE REST WITH SPRING - MASTER CLASS](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)**
|
|
||||||
|
|
||||||
And here's the Master Class of Learn Spring Security: <br/>
|
Here's the new "Learn Spring" course: <br/>
|
||||||
**[>> LEARN SPRING SECURITY - MASTER CLASS](http://www.baeldung.com/learn-spring-security-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=lss#master-class)**
|
**[>> LEARN SPRING - THE MASTER CLASS](https://www.baeldung.com/learn-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=ls#master-class)**
|
||||||
|
|
||||||
|
Here's the Master Class of "REST With Spring" (along with the new announced Boot 2 material): <br/>
|
||||||
|
**[>> THE REST WITH SPRING - MASTER CLASS](https://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)**
|
||||||
|
|
||||||
|
And here's the Master Class of "Learn Spring Security": <br/>
|
||||||
|
**[>> LEARN SPRING SECURITY - MASTER CLASS](https://www.baeldung.com/learn-spring-security-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=lss#master-class)**
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@ -15,7 +19,7 @@ Java and Spring Tutorials
|
|||||||
|
|
||||||
This project is **a collection of small and focused tutorials** - each covering a single and well defined area of development in the Java ecosystem.
|
This project is **a collection of small and focused tutorials** - each covering a single and well defined area of development in the Java ecosystem.
|
||||||
A strong focus of these is, of course, the Spring Framework - Spring, Spring Boot and Spring Security.
|
A strong focus of these is, of course, the Spring Framework - Spring, Spring Boot and Spring Security.
|
||||||
In additional to Spring, the following technologies are in focus: `core Java`, `Jackson`, `HttpClient`, `Guava`.
|
In additional to Spring, the modules here are covering a number of aspects in Java.
|
||||||
|
|
||||||
|
|
||||||
Building the project
|
Building the project
|
||||||
@ -32,8 +36,15 @@ 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
|
|
||||||
|
|
||||||
|
Working with the IDE
|
||||||
|
====================
|
||||||
|
This repo contains a large number of modules.
|
||||||
|
When you're working with an individual module, there's no need to import all of them (or build all of them) - you can simply import that particular module in either Eclipse or IntelliJ.
|
||||||
|
|
||||||
|
|
||||||
|
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>
|
@ -1,6 +1,9 @@
|
|||||||
## Relevant articles:
|
## Relevant Articles:
|
||||||
|
|
||||||
- [Java Two Pointer Technique](https://www.baeldung.com/java-two-pointer-technique)
|
- [Java Two Pointer Technique](https://www.baeldung.com/java-two-pointer-technique)
|
||||||
- [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)
|
||||||
|
@ -30,6 +30,30 @@
|
|||||||
<artifactId>guava</artifactId>
|
<artifactId>guava</artifactId>
|
||||||
<version>${guava.version}</version>
|
<version>${guava.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.squareup.retrofit2</groupId>
|
||||||
|
<artifactId>retrofit</artifactId>
|
||||||
|
<version>${retrofit.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.squareup.retrofit2</groupId>
|
||||||
|
<artifactId>converter-jackson</artifactId>
|
||||||
|
<version>${retrofit.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.commons</groupId>
|
||||||
|
<artifactId>commons-lang3</artifactId>
|
||||||
|
<version>3.8.1</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>pl.pragmatists</groupId>
|
||||||
|
<artifactId>JUnitParams</artifactId>
|
||||||
|
<version>1.1.0</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
@ -48,5 +72,6 @@
|
|||||||
<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>
|
<commons-collections4.version>4.3</commons-collections4.version>
|
||||||
<guava.version>28.0-jre</guava.version>
|
<guava.version>28.0-jre</guava.version>
|
||||||
|
<retrofit.version>2.6.0</retrofit.version>
|
||||||
</properties>
|
</properties>
|
||||||
</project>
|
</project>
|
@ -27,6 +27,7 @@ public class SortedListChecker {
|
|||||||
if (previous.compareTo(current) > 0) {
|
if (previous.compareTo(current) > 0) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
previous = current;
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@ -43,6 +44,7 @@ public class SortedListChecker {
|
|||||||
if (employeeComparator.compare(previous, current) > 0) {
|
if (employeeComparator.compare(previous, current) > 0) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
previous = current;
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,35 @@
|
|||||||
|
package com.baeldung.algorithms.interpolationsearch;
|
||||||
|
|
||||||
|
public class InterpolationSearch {
|
||||||
|
|
||||||
|
public static int interpolationSearch(int[] data, int item) {
|
||||||
|
|
||||||
|
int highEnd = (data.length - 1);
|
||||||
|
int lowEnd = 0;
|
||||||
|
|
||||||
|
while (item >= data[lowEnd] && item <= data[highEnd] && lowEnd <= highEnd) {
|
||||||
|
|
||||||
|
int probe = lowEnd + (highEnd - lowEnd) * (item - data[lowEnd]) / (data[highEnd] - data[lowEnd]);
|
||||||
|
|
||||||
|
if (highEnd == lowEnd) {
|
||||||
|
if (data[lowEnd] == item) {
|
||||||
|
return lowEnd;
|
||||||
|
} else {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data[probe] == item) {
|
||||||
|
return probe;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data[probe] < item) {
|
||||||
|
lowEnd = probe + 1;
|
||||||
|
} else {
|
||||||
|
highEnd = probe - 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,45 @@
|
|||||||
|
package com.baeldung.algorithms.kmeans;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Encapsulates all coordinates for a particular cluster centroid.
|
||||||
|
*/
|
||||||
|
public class Centroid {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The centroid coordinates.
|
||||||
|
*/
|
||||||
|
private final Map<String, Double> coordinates;
|
||||||
|
|
||||||
|
public Centroid(Map<String, Double> coordinates) {
|
||||||
|
this.coordinates = coordinates;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, Double> getCoordinates() {
|
||||||
|
return coordinates;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object o) {
|
||||||
|
if (this == o) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (o == null || getClass() != o.getClass()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
Centroid centroid = (Centroid) o;
|
||||||
|
return Objects.equals(getCoordinates(), centroid.getCoordinates());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
return Objects.hash(getCoordinates());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "Centroid " + coordinates;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,20 @@
|
|||||||
|
package com.baeldung.algorithms.kmeans;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Defines a contract to calculate distance between two feature vectors. The less the
|
||||||
|
* calculated distance, the more two items are similar to each other.
|
||||||
|
*/
|
||||||
|
public interface Distance {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calculates the distance between two feature vectors.
|
||||||
|
*
|
||||||
|
* @param f1 The first set of features.
|
||||||
|
* @param f2 The second set of features.
|
||||||
|
* @return Calculated distance.
|
||||||
|
* @throws IllegalArgumentException If the given feature vectors are invalid.
|
||||||
|
*/
|
||||||
|
double calculate(Map<String, Double> f1, Map<String, Double> f2);
|
||||||
|
}
|
@ -0,0 +1,23 @@
|
|||||||
|
package com.baeldung.algorithms.kmeans;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Encapsulates methods to calculates errors between centroid and the cluster members.
|
||||||
|
*/
|
||||||
|
public class Errors {
|
||||||
|
|
||||||
|
public static double sse(Map<Centroid, List<Record>> clustered, Distance distance) {
|
||||||
|
double sum = 0;
|
||||||
|
for (Map.Entry<Centroid, List<Record>> entry : clustered.entrySet()) {
|
||||||
|
Centroid centroid = entry.getKey();
|
||||||
|
for (Record record : entry.getValue()) {
|
||||||
|
double d = distance.calculate(centroid.getCoordinates(), record.getFeatures());
|
||||||
|
sum += Math.pow(d, 2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return sum;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,26 @@
|
|||||||
|
package com.baeldung.algorithms.kmeans;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calculates the distance between two items using the Euclidean formula.
|
||||||
|
*/
|
||||||
|
public class EuclideanDistance implements Distance {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public double calculate(Map<String, Double> f1, Map<String, Double> f2) {
|
||||||
|
if (f1 == null || f2 == null) {
|
||||||
|
throw new IllegalArgumentException("Feature vectors can't be null");
|
||||||
|
}
|
||||||
|
|
||||||
|
double sum = 0;
|
||||||
|
for (String key : f1.keySet()) {
|
||||||
|
Double v1 = f1.get(key);
|
||||||
|
Double v2 = f2.get(key);
|
||||||
|
|
||||||
|
if (v1 != null && v2 != null) sum += Math.pow(v1 - v2, 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Math.sqrt(sum);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,236 @@
|
|||||||
|
package com.baeldung.algorithms.kmeans;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Random;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
import static java.util.stream.Collectors.toList;
|
||||||
|
import static java.util.stream.Collectors.toSet;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Encapsulates an implementation of KMeans clustering algorithm.
|
||||||
|
*
|
||||||
|
* @author Ali Dehghani
|
||||||
|
*/
|
||||||
|
public class KMeans {
|
||||||
|
|
||||||
|
private KMeans() {
|
||||||
|
throw new IllegalAccessError("You shouldn't call this constructor");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Will be used to generate random numbers.
|
||||||
|
*/
|
||||||
|
private static final Random random = new Random();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Performs the K-Means clustering algorithm on the given dataset.
|
||||||
|
*
|
||||||
|
* @param records The dataset.
|
||||||
|
* @param k Number of Clusters.
|
||||||
|
* @param distance To calculate the distance between two items.
|
||||||
|
* @param maxIterations Upper bound for the number of iterations.
|
||||||
|
* @return K clusters along with their features.
|
||||||
|
*/
|
||||||
|
public static Map<Centroid, List<Record>> fit(List<Record> records, int k, Distance distance, int maxIterations) {
|
||||||
|
applyPreconditions(records, k, distance, maxIterations);
|
||||||
|
|
||||||
|
List<Centroid> centroids = randomCentroids(records, k);
|
||||||
|
Map<Centroid, List<Record>> clusters = new HashMap<>();
|
||||||
|
Map<Centroid, List<Record>> lastState = new HashMap<>();
|
||||||
|
|
||||||
|
// iterate for a pre-defined number of times
|
||||||
|
for (int i = 0; i < maxIterations; i++) {
|
||||||
|
boolean isLastIteration = i == maxIterations - 1;
|
||||||
|
|
||||||
|
// in each iteration we should find the nearest centroid for each record
|
||||||
|
for (Record record : records) {
|
||||||
|
Centroid centroid = nearestCentroid(record, centroids, distance);
|
||||||
|
assignToCluster(clusters, record, centroid);
|
||||||
|
}
|
||||||
|
|
||||||
|
// if the assignment does not change, then the algorithm terminates
|
||||||
|
boolean shouldTerminate = isLastIteration || clusters.equals(lastState);
|
||||||
|
lastState = clusters;
|
||||||
|
if (shouldTerminate) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
// at the end of each iteration we should relocate the centroids
|
||||||
|
centroids = relocateCentroids(clusters);
|
||||||
|
clusters = new HashMap<>();
|
||||||
|
}
|
||||||
|
|
||||||
|
return lastState;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Move all cluster centroids to the average of all assigned features.
|
||||||
|
*
|
||||||
|
* @param clusters The current cluster configuration.
|
||||||
|
* @return Collection of new and relocated centroids.
|
||||||
|
*/
|
||||||
|
private static List<Centroid> relocateCentroids(Map<Centroid, List<Record>> clusters) {
|
||||||
|
return clusters
|
||||||
|
.entrySet()
|
||||||
|
.stream()
|
||||||
|
.map(e -> average(e.getKey(), e.getValue()))
|
||||||
|
.collect(toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Moves the given centroid to the average position of all assigned features. If
|
||||||
|
* the centroid has no feature in its cluster, then there would be no need for a
|
||||||
|
* relocation. Otherwise, for each entry we calculate the average of all records
|
||||||
|
* first by summing all the entries and then dividing the final summation value by
|
||||||
|
* the number of records.
|
||||||
|
*
|
||||||
|
* @param centroid The centroid to move.
|
||||||
|
* @param records The assigned features.
|
||||||
|
* @return The moved centroid.
|
||||||
|
*/
|
||||||
|
private static Centroid average(Centroid centroid, List<Record> records) {
|
||||||
|
// if this cluster is empty, then we shouldn't move the centroid
|
||||||
|
if (records == null || records.isEmpty()) {
|
||||||
|
return centroid;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Since some records don't have all possible attributes, we initialize
|
||||||
|
// average coordinates equal to current centroid coordinates
|
||||||
|
Map<String, Double> average = centroid.getCoordinates();
|
||||||
|
|
||||||
|
// The average function works correctly if we clear all coordinates corresponding
|
||||||
|
// to present record attributes
|
||||||
|
records
|
||||||
|
.stream()
|
||||||
|
.flatMap(e -> e
|
||||||
|
.getFeatures()
|
||||||
|
.keySet()
|
||||||
|
.stream())
|
||||||
|
.forEach(k -> average.put(k, 0.0));
|
||||||
|
|
||||||
|
for (Record record : records) {
|
||||||
|
record
|
||||||
|
.getFeatures()
|
||||||
|
.forEach((k, v) -> average.compute(k, (k1, currentValue) -> v + currentValue));
|
||||||
|
}
|
||||||
|
|
||||||
|
average.forEach((k, v) -> average.put(k, v / records.size()));
|
||||||
|
|
||||||
|
return new Centroid(average);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Assigns a feature vector to the given centroid. If this is the first assignment for this centroid,
|
||||||
|
* first we should create the list.
|
||||||
|
*
|
||||||
|
* @param clusters The current cluster configuration.
|
||||||
|
* @param record The feature vector.
|
||||||
|
* @param centroid The centroid.
|
||||||
|
*/
|
||||||
|
private static void assignToCluster(Map<Centroid, List<Record>> clusters, Record record, Centroid centroid) {
|
||||||
|
clusters.compute(centroid, (key, list) -> {
|
||||||
|
if (list == null) {
|
||||||
|
list = new ArrayList<>();
|
||||||
|
}
|
||||||
|
|
||||||
|
list.add(record);
|
||||||
|
return list;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* With the help of the given distance calculator, iterates through centroids and finds the
|
||||||
|
* nearest one to the given record.
|
||||||
|
*
|
||||||
|
* @param record The feature vector to find a centroid for.
|
||||||
|
* @param centroids Collection of all centroids.
|
||||||
|
* @param distance To calculate the distance between two items.
|
||||||
|
* @return The nearest centroid to the given feature vector.
|
||||||
|
*/
|
||||||
|
private static Centroid nearestCentroid(Record record, List<Centroid> centroids, Distance distance) {
|
||||||
|
double minimumDistance = Double.MAX_VALUE;
|
||||||
|
Centroid nearest = null;
|
||||||
|
|
||||||
|
for (Centroid centroid : centroids) {
|
||||||
|
double currentDistance = distance.calculate(record.getFeatures(), centroid.getCoordinates());
|
||||||
|
|
||||||
|
if (currentDistance < minimumDistance) {
|
||||||
|
minimumDistance = currentDistance;
|
||||||
|
nearest = centroid;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nearest;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generates k random centroids. Before kicking-off the centroid generation process,
|
||||||
|
* first we calculate the possible value range for each attribute. Then when
|
||||||
|
* we're going to generate the centroids, we generate random coordinates in
|
||||||
|
* the [min, max] range for each attribute.
|
||||||
|
*
|
||||||
|
* @param records The dataset which helps to calculate the [min, max] range for
|
||||||
|
* each attribute.
|
||||||
|
* @param k Number of clusters.
|
||||||
|
* @return Collections of randomly generated centroids.
|
||||||
|
*/
|
||||||
|
private static List<Centroid> randomCentroids(List<Record> records, int k) {
|
||||||
|
List<Centroid> centroids = new ArrayList<>();
|
||||||
|
Map<String, Double> maxs = new HashMap<>();
|
||||||
|
Map<String, Double> mins = new HashMap<>();
|
||||||
|
|
||||||
|
for (Record record : records) {
|
||||||
|
record
|
||||||
|
.getFeatures()
|
||||||
|
.forEach((key, value) -> {
|
||||||
|
// compares the value with the current max and choose the bigger value between them
|
||||||
|
maxs.compute(key, (k1, max) -> max == null || value > max ? value : max);
|
||||||
|
|
||||||
|
// compare the value with the current min and choose the smaller value between them
|
||||||
|
mins.compute(key, (k1, min) -> min == null || value < min ? value : min);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Set<String> attributes = records
|
||||||
|
.stream()
|
||||||
|
.flatMap(e -> e
|
||||||
|
.getFeatures()
|
||||||
|
.keySet()
|
||||||
|
.stream())
|
||||||
|
.collect(toSet());
|
||||||
|
for (int i = 0; i < k; i++) {
|
||||||
|
Map<String, Double> coordinates = new HashMap<>();
|
||||||
|
for (String attribute : attributes) {
|
||||||
|
double max = maxs.get(attribute);
|
||||||
|
double min = mins.get(attribute);
|
||||||
|
coordinates.put(attribute, random.nextDouble() * (max - min) + min);
|
||||||
|
}
|
||||||
|
|
||||||
|
centroids.add(new Centroid(coordinates));
|
||||||
|
}
|
||||||
|
|
||||||
|
return centroids;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void applyPreconditions(List<Record> records, int k, Distance distance, int maxIterations) {
|
||||||
|
if (records == null || records.isEmpty()) {
|
||||||
|
throw new IllegalArgumentException("The dataset can't be empty");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (k <= 1) {
|
||||||
|
throw new IllegalArgumentException("It doesn't make sense to have less than or equal to 1 cluster");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (distance == null) {
|
||||||
|
throw new IllegalArgumentException("The distance calculator is required");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (maxIterations <= 0) {
|
||||||
|
throw new IllegalArgumentException("Max iterations should be a positive number");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,144 @@
|
|||||||
|
package com.baeldung.algorithms.kmeans;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import okhttp3.OkHttpClient;
|
||||||
|
import retrofit2.Retrofit;
|
||||||
|
import retrofit2.converter.jackson.JacksonConverterFactory;
|
||||||
|
|
||||||
|
import static java.util.stream.Collectors.toSet;
|
||||||
|
|
||||||
|
public class LastFm {
|
||||||
|
|
||||||
|
private static OkHttpClient okHttp = new OkHttpClient.Builder()
|
||||||
|
.addInterceptor(new LastFmService.Authenticator("put your API key here"))
|
||||||
|
.build();
|
||||||
|
|
||||||
|
private static Retrofit retrofit = new Retrofit.Builder()
|
||||||
|
.client(okHttp)
|
||||||
|
.addConverterFactory(JacksonConverterFactory.create())
|
||||||
|
.baseUrl("http://ws.audioscrobbler.com/")
|
||||||
|
.build();
|
||||||
|
|
||||||
|
private static LastFmService lastFm = retrofit.create(LastFmService.class);
|
||||||
|
|
||||||
|
private static ObjectMapper mapper = new ObjectMapper();
|
||||||
|
|
||||||
|
public static void main(String[] args) throws IOException {
|
||||||
|
List<String> artists = getTop100Artists();
|
||||||
|
Set<String> tags = getTop100Tags();
|
||||||
|
List<Record> records = datasetWithTaggedArtists(artists, tags);
|
||||||
|
|
||||||
|
Map<Centroid, List<Record>> clusters = KMeans.fit(records, 7, new EuclideanDistance(), 1000);
|
||||||
|
// Print the cluster configuration
|
||||||
|
clusters.forEach((key, value) -> {
|
||||||
|
System.out.println("------------------------------ CLUSTER -----------------------------------");
|
||||||
|
|
||||||
|
System.out.println(sortedCentroid(key));
|
||||||
|
String members = String.join(", ", value
|
||||||
|
.stream()
|
||||||
|
.map(Record::getDescription)
|
||||||
|
.collect(toSet()));
|
||||||
|
System.out.print(members);
|
||||||
|
|
||||||
|
System.out.println();
|
||||||
|
System.out.println();
|
||||||
|
});
|
||||||
|
|
||||||
|
Map<String, Object> json = convertToD3CompatibleMap(clusters);
|
||||||
|
System.out.println(mapper.writeValueAsString(json));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Map<String, Object> convertToD3CompatibleMap(Map<Centroid, List<Record>> clusters) {
|
||||||
|
Map<String, Object> json = new HashMap<>();
|
||||||
|
json.put("name", "Musicians");
|
||||||
|
List<Map<String, Object>> children = new ArrayList<>();
|
||||||
|
clusters.forEach((key, value) -> {
|
||||||
|
Map<String, Object> child = new HashMap<>();
|
||||||
|
child.put("name", dominantGenre(sortedCentroid(key)));
|
||||||
|
List<Map<String, String>> nested = new ArrayList<>();
|
||||||
|
for (Record record : value) {
|
||||||
|
nested.add(Collections.singletonMap("name", record.getDescription()));
|
||||||
|
}
|
||||||
|
child.put("children", nested);
|
||||||
|
|
||||||
|
children.add(child);
|
||||||
|
});
|
||||||
|
json.put("children", children);
|
||||||
|
return json;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String dominantGenre(Centroid centroid) {
|
||||||
|
return centroid
|
||||||
|
.getCoordinates()
|
||||||
|
.keySet()
|
||||||
|
.stream()
|
||||||
|
.limit(2)
|
||||||
|
.collect(Collectors.joining(", "));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Centroid sortedCentroid(Centroid key) {
|
||||||
|
List<Map.Entry<String, Double>> entries = new ArrayList<>(key
|
||||||
|
.getCoordinates()
|
||||||
|
.entrySet());
|
||||||
|
entries.sort((e1, e2) -> e2
|
||||||
|
.getValue()
|
||||||
|
.compareTo(e1.getValue()));
|
||||||
|
|
||||||
|
Map<String, Double> sorted = new LinkedHashMap<>();
|
||||||
|
for (Map.Entry<String, Double> entry : entries) {
|
||||||
|
sorted.put(entry.getKey(), entry.getValue());
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Centroid(sorted);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<Record> datasetWithTaggedArtists(List<String> artists, Set<String> topTags) throws IOException {
|
||||||
|
List<Record> records = new ArrayList<>();
|
||||||
|
for (String artist : artists) {
|
||||||
|
Map<String, Double> tags = lastFm
|
||||||
|
.topTagsFor(artist)
|
||||||
|
.execute()
|
||||||
|
.body()
|
||||||
|
.all();
|
||||||
|
|
||||||
|
// Only keep popular tags.
|
||||||
|
tags
|
||||||
|
.entrySet()
|
||||||
|
.removeIf(e -> !topTags.contains(e.getKey()));
|
||||||
|
|
||||||
|
records.add(new Record(artist, tags));
|
||||||
|
}
|
||||||
|
return records;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Set<String> getTop100Tags() throws IOException {
|
||||||
|
return lastFm
|
||||||
|
.topTags()
|
||||||
|
.execute()
|
||||||
|
.body()
|
||||||
|
.all();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<String> getTop100Artists() throws IOException {
|
||||||
|
List<String> artists = new ArrayList<>();
|
||||||
|
for (int i = 1; i <= 2; i++) {
|
||||||
|
artists.addAll(lastFm
|
||||||
|
.topArtists(i)
|
||||||
|
.execute()
|
||||||
|
.body()
|
||||||
|
.all());
|
||||||
|
}
|
||||||
|
|
||||||
|
return artists;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,118 @@
|
|||||||
|
package com.baeldung.algorithms.kmeans;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonAutoDetect;
|
||||||
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
|
import okhttp3.HttpUrl;
|
||||||
|
import okhttp3.Interceptor;
|
||||||
|
import okhttp3.Request;
|
||||||
|
import okhttp3.Response;
|
||||||
|
import retrofit2.Call;
|
||||||
|
import retrofit2.http.GET;
|
||||||
|
import retrofit2.http.Query;
|
||||||
|
|
||||||
|
import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.ANY;
|
||||||
|
import static java.util.stream.Collectors.toList;
|
||||||
|
|
||||||
|
public interface LastFmService {
|
||||||
|
|
||||||
|
@GET("/2.0/?method=chart.gettopartists&format=json&limit=50")
|
||||||
|
Call<Artists> topArtists(@Query("page") int page);
|
||||||
|
|
||||||
|
@GET("/2.0/?method=artist.gettoptags&format=json&limit=20&autocorrect=1")
|
||||||
|
Call<Tags> topTagsFor(@Query("artist") String artist);
|
||||||
|
|
||||||
|
@GET("/2.0/?method=chart.gettoptags&format=json&limit=100")
|
||||||
|
Call<TopTags> topTags();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* HTTP interceptor to intercept all HTTP requests and add the API key to them.
|
||||||
|
*/
|
||||||
|
class Authenticator implements Interceptor {
|
||||||
|
|
||||||
|
private final String apiKey;
|
||||||
|
|
||||||
|
Authenticator(String apiKey) {
|
||||||
|
this.apiKey = apiKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Response intercept(Chain chain) throws IOException {
|
||||||
|
HttpUrl url = chain
|
||||||
|
.request()
|
||||||
|
.url()
|
||||||
|
.newBuilder()
|
||||||
|
.addQueryParameter("api_key", apiKey)
|
||||||
|
.build();
|
||||||
|
Request request = chain
|
||||||
|
.request()
|
||||||
|
.newBuilder()
|
||||||
|
.url(url)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
return chain.proceed(request);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@JsonAutoDetect(fieldVisibility = ANY)
|
||||||
|
class TopTags {
|
||||||
|
|
||||||
|
private Map<String, Object> tags;
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public Set<String> all() {
|
||||||
|
List<Map<String, Object>> topTags = (List<Map<String, Object>>) tags.get("tag");
|
||||||
|
return topTags
|
||||||
|
.stream()
|
||||||
|
.map(e -> ((String) e.get("name")))
|
||||||
|
.collect(Collectors.toSet());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@JsonAutoDetect(fieldVisibility = ANY)
|
||||||
|
class Tags {
|
||||||
|
|
||||||
|
@JsonProperty("toptags") private Map<String, Object> topTags;
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public Map<String, Double> all() {
|
||||||
|
try {
|
||||||
|
Map<String, Double> all = new HashMap<>();
|
||||||
|
List<Map<String, Object>> tags = (List<Map<String, Object>>) topTags.get("tag");
|
||||||
|
for (Map<String, Object> tag : tags) {
|
||||||
|
all.put(((String) tag.get("name")), ((Integer) tag.get("count")).doubleValue());
|
||||||
|
}
|
||||||
|
|
||||||
|
return all;
|
||||||
|
} catch (Exception e) {
|
||||||
|
return Collections.emptyMap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@JsonAutoDetect(fieldVisibility = ANY)
|
||||||
|
class Artists {
|
||||||
|
|
||||||
|
private Map<String, Object> artists;
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public List<String> all() {
|
||||||
|
try {
|
||||||
|
List<Map<String, Object>> artists = (List<Map<String, Object>>) this.artists.get("artist");
|
||||||
|
return artists
|
||||||
|
.stream()
|
||||||
|
.map(e -> ((String) e.get("name")))
|
||||||
|
.collect(toList());
|
||||||
|
} catch (Exception e) {
|
||||||
|
return Collections.emptyList();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,65 @@
|
|||||||
|
package com.baeldung.algorithms.kmeans;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Encapsulates all feature values for a few attributes. Optionally each record
|
||||||
|
* can be described with the {@link #description} field.
|
||||||
|
*/
|
||||||
|
public class Record {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The record description. For example, this can be the artist name for the famous musician
|
||||||
|
* example.
|
||||||
|
*/
|
||||||
|
private final String description;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Encapsulates all attributes and their corresponding values, i.e. features.
|
||||||
|
*/
|
||||||
|
private final Map<String, Double> features;
|
||||||
|
|
||||||
|
public Record(String description, Map<String, Double> features) {
|
||||||
|
this.description = description;
|
||||||
|
this.features = features;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Record(Map<String, Double> features) {
|
||||||
|
this("", features);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getDescription() {
|
||||||
|
return description;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, Double> getFeatures() {
|
||||||
|
return features;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
String prefix = description == null || description
|
||||||
|
.trim()
|
||||||
|
.isEmpty() ? "Record" : description;
|
||||||
|
|
||||||
|
return prefix + ": " + features;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object o) {
|
||||||
|
if (this == o) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (o == null || getClass() != o.getClass()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
Record record = (Record) o;
|
||||||
|
return Objects.equals(getDescription(), record.getDescription()) && Objects.equals(getFeatures(), record.getFeatures());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
return Objects.hash(getDescription(), getFeatures());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,49 @@
|
|||||||
|
package com.baeldung.algorithms.printtriangles;
|
||||||
|
|
||||||
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
|
||||||
|
public class PrintTriangleExamples {
|
||||||
|
|
||||||
|
public static String printARightAngledTriangle(int N) {
|
||||||
|
StringBuilder result = new StringBuilder();
|
||||||
|
for (int r = 1; r <= N; r++) {
|
||||||
|
for (int j = 1; j <= r; j++) {
|
||||||
|
result.append("*");
|
||||||
|
}
|
||||||
|
result.append(System.lineSeparator());
|
||||||
|
}
|
||||||
|
return result.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String printAnIsoscelesTriangle(int N) {
|
||||||
|
StringBuilder result = new StringBuilder();
|
||||||
|
for (int r = 1; r <= N; r++) {
|
||||||
|
for (int sp = 1; sp <= N - r; sp++) {
|
||||||
|
result.append(" ");
|
||||||
|
}
|
||||||
|
for (int c = 1; c <= (r * 2) - 1; c++) {
|
||||||
|
result.append("*");
|
||||||
|
}
|
||||||
|
result.append(System.lineSeparator());
|
||||||
|
}
|
||||||
|
return result.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String printAnIsoscelesTriangleUsingSubstring(int N) {
|
||||||
|
StringBuilder result = new StringBuilder();
|
||||||
|
String helperString = StringUtils.repeat(' ', N - 1) + StringUtils.repeat('*', N * 2 - 1);
|
||||||
|
|
||||||
|
for (int r = 0; r < N; r++) {
|
||||||
|
result.append(helperString.substring(r, N + 2 * r));
|
||||||
|
result.append(System.lineSeparator());
|
||||||
|
}
|
||||||
|
return result.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
System.out.println(printARightAngledTriangle(5));
|
||||||
|
System.out.println(printAnIsoscelesTriangle(5));
|
||||||
|
System.out.println(printAnIsoscelesTriangleUsingSubstring(5));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,30 @@
|
|||||||
|
package com.baeldung.algorithms.stringsortingbynumber;
|
||||||
|
|
||||||
|
import java.util.Comparator;
|
||||||
|
|
||||||
|
public final class NaturalOrderComparators {
|
||||||
|
|
||||||
|
private static final String DIGIT_AND_DECIMAL_REGEX = "[^\\d.]";
|
||||||
|
|
||||||
|
private NaturalOrderComparators() {
|
||||||
|
throw new AssertionError("Let's keep this static");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Comparator<String> createNaturalOrderRegexComparator() {
|
||||||
|
return Comparator.comparingDouble(NaturalOrderComparators::parseStringToNumber);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static double parseStringToNumber(String input){
|
||||||
|
|
||||||
|
final String digitsOnly = input.replaceAll(DIGIT_AND_DECIMAL_REGEX, "");
|
||||||
|
|
||||||
|
if("".equals(digitsOnly)) return 0;
|
||||||
|
|
||||||
|
try{
|
||||||
|
return Double.parseDouble(digitsOnly);
|
||||||
|
}catch (NumberFormatException nfe){
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
3384
algorithms-miscellaneous-3/src/main/resources/kmeans/artists.json
Normal file
3384
algorithms-miscellaneous-3/src/main/resources/kmeans/artists.json
Normal file
File diff suppressed because it is too large
Load Diff
490
algorithms-miscellaneous-3/src/main/resources/kmeans/lastfm.json
Normal file
490
algorithms-miscellaneous-3/src/main/resources/kmeans/lastfm.json
Normal file
@ -0,0 +1,490 @@
|
|||||||
|
{
|
||||||
|
"children": [
|
||||||
|
{
|
||||||
|
"children": [
|
||||||
|
{
|
||||||
|
"name": "Radiohead"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Red Hot Chili Peppers"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Coldplay"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Nirvana"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Panic! at the Disco"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "The Cure"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Linkin Park"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Radiohead"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Red Hot Chili Peppers"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Coldplay"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Nirvana"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Panic! at the Disco"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "The Cure"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Linkin Park"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Muse"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Maroon 5"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Foo Fighters"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Paramore"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Oasis"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Fall Out Boy"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "OneRepublic"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Weezer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "System of a Down"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "The White Stripes"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"name": "rock, alternative"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"children": [
|
||||||
|
{
|
||||||
|
"name": "Lil Nas X"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Post Malone"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Drake"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Kanye West"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Kendrick Lamar"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Tyler, the Creator"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Eminem"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Childish Gambino"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Frank Ocean"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Lil Nas X"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Post Malone"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Drake"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Kanye West"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Kendrick Lamar"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Tyler, the Creator"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Eminem"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Childish Gambino"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Frank Ocean"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Lizzo"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Travi$ Scott"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "A$AP Rocky"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Nicki Minaj"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "xxxtentacion"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"name": "Hip-Hop, rap"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"children": [
|
||||||
|
{
|
||||||
|
"name": "Arctic Monkeys"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Imagine Dragons"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "The Killers"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Gorillaz"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "The Black Keys"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Arctic Monkeys"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Imagine Dragons"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "The Killers"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Gorillaz"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "The Black Keys"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Twenty One Pilots"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Ellie Goulding"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Florence + the Machine"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Vampire Weekend"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "The Smiths"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "The Strokes"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "MGMT"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Foster the People"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Two Door Cinema Club"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Cage the Elephant"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Arcade Fire"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "The 1975"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"name": "indie, alternative"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"children": [
|
||||||
|
{
|
||||||
|
"name": "Ed Sheeran"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Tame Impala"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Ed Sheeran"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Tame Impala"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Green Day"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Metallica"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "blink-182"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Bon Iver"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "The Clash"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"name": "rock, punk rock"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"children": [
|
||||||
|
{
|
||||||
|
"name": "Calvin Harris"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "The Weeknd"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "The Chainsmokers"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Daft Punk"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Marshmello"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "David Guetta"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Calvin Harris"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "The Weeknd"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "The Chainsmokers"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Daft Punk"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Marshmello"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "David Guetta"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Avicii"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Kygo"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Martin Garrix"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Major Lazer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Depeche Mode"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"name": "electronic, dance"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"children": [
|
||||||
|
{
|
||||||
|
"name": "Queen"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "The Beatles"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "David Bowie"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Fleetwood Mac"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Pink Floyd"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "The Rolling Stones"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Led Zeppelin"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Queen"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "The Beatles"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "David Bowie"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Fleetwood Mac"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Pink Floyd"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "The Rolling Stones"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Led Zeppelin"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Elton John"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"name": "classic rock, rock"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"children": [
|
||||||
|
{
|
||||||
|
"name": "Billie Eilish"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Ariana Grande"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Taylor Swift"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Beyoncé"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Shawn Mendes"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Rihanna"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Lana Del Rey"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Katy Perry"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Lady Gaga"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Miley Cyrus"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Mark Ronson"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Madonna"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Lorde"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Khalid"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Billie Eilish"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Ariana Grande"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Taylor Swift"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Beyoncé"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Shawn Mendes"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Rihanna"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Lana Del Rey"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Katy Perry"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Lady Gaga"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Miley Cyrus"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Mark Ronson"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Madonna"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Lorde"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Khalid"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Sia"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Sam Smith"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Halsey"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Michael Jackson"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Charli XCX"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Britney Spears"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Dua Lipa"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Jonas Brothers"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Bruno Mars"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Carly Rae Jepsen"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "P!nk"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Adele"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"name": "pop, female vocalists"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"name": "Musicians"
|
||||||
|
}
|
@ -0,0 +1,68 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<style>
|
||||||
|
.node circle {
|
||||||
|
fill: #fff;
|
||||||
|
stroke: steelblue;
|
||||||
|
stroke-width: 1.5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.node {
|
||||||
|
font: 10px sans-serif;
|
||||||
|
}
|
||||||
|
|
||||||
|
.link {
|
||||||
|
fill: none;
|
||||||
|
stroke: #ccc;
|
||||||
|
stroke-width: 1.5px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
<body>
|
||||||
|
<script src="http://d3js.org/d3.v3.min.js"></script>
|
||||||
|
<script>
|
||||||
|
var diameter = 1100;
|
||||||
|
var tree = d3.layout.tree()
|
||||||
|
.size([360, diameter / 2 - 300])
|
||||||
|
.separation(function (a, b) {
|
||||||
|
return (a.parent == b.parent ? 1 : 2) / a.depth;
|
||||||
|
});
|
||||||
|
var diagonal = d3.svg.diagonal.radial()
|
||||||
|
.projection(function (d) {
|
||||||
|
return [d.y, d.x / 180 * Math.PI];
|
||||||
|
});
|
||||||
|
var svg = d3.select("body").append("svg")
|
||||||
|
.attr("width", diameter)
|
||||||
|
.attr("height", diameter - 150)
|
||||||
|
.append("g")
|
||||||
|
.attr("transform", "translate(" + diameter / 2 + "," + diameter / 2 + ")");
|
||||||
|
d3.json("lastfm.json", function (error, root) {
|
||||||
|
var nodes = tree.nodes(root),
|
||||||
|
links = tree.links(nodes);
|
||||||
|
var link = svg.selectAll(".link")
|
||||||
|
.data(links)
|
||||||
|
.enter().append("path")
|
||||||
|
.attr("class", "link")
|
||||||
|
.attr("d", diagonal);
|
||||||
|
var node = svg.selectAll(".node")
|
||||||
|
.data(nodes)
|
||||||
|
.enter().append("g")
|
||||||
|
.attr("class", "node")
|
||||||
|
.attr("transform", function (d) {
|
||||||
|
return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")";
|
||||||
|
})
|
||||||
|
node.append("circle")
|
||||||
|
.attr("r", 4.5);
|
||||||
|
node.append("text")
|
||||||
|
.attr("dy", ".31em")
|
||||||
|
.attr("text-anchor", function (d) {
|
||||||
|
return d.x < 180 ? "start" : "end";
|
||||||
|
})
|
||||||
|
.attr("transform", function (d) {
|
||||||
|
return d.x < 180 ? "translate(8)" : "rotate(180)translate(-8)";
|
||||||
|
})
|
||||||
|
.text(function (d) {
|
||||||
|
return d.name;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
d3.select(self.frameElement).style("height", diameter - 150 + "px");
|
||||||
|
</script>
|
@ -0,0 +1,29 @@
|
|||||||
|
package com.baeldung.algorithms.interpolationsearch;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class InterpolationSearchUnitTest {
|
||||||
|
|
||||||
|
private int[] myData;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setUp() {
|
||||||
|
myData = new int[]{13,21,34,55,69,73,84,101};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSortedArray_whenLookingFor84_thenReturn6() {
|
||||||
|
int pos = InterpolationSearch.interpolationSearch(myData, 84);
|
||||||
|
assertEquals(6, pos);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSortedArray_whenLookingFor19_thenReturnMinusOne() {
|
||||||
|
int pos = InterpolationSearch.interpolationSearch(myData, 19);
|
||||||
|
assertEquals(-1, pos);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,93 @@
|
|||||||
|
package com.baeldung.algorithms.printtriangles;
|
||||||
|
|
||||||
|
import junitparams.JUnitParamsRunner;
|
||||||
|
import junitparams.Parameters;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
@RunWith(JUnitParamsRunner.class)
|
||||||
|
public class PrintTriangleExamplesUnitTest {
|
||||||
|
|
||||||
|
private static Object[][] rightAngledTriangles() {
|
||||||
|
String expected0 = "";
|
||||||
|
|
||||||
|
String expected2 = "*" + System.lineSeparator()
|
||||||
|
+ "**" + System.lineSeparator();
|
||||||
|
|
||||||
|
String expected5 = "*" + System.lineSeparator()
|
||||||
|
+ "**" + System.lineSeparator()
|
||||||
|
+ "***" + System.lineSeparator()
|
||||||
|
+ "****" + System.lineSeparator()
|
||||||
|
+ "*****" + System.lineSeparator();
|
||||||
|
|
||||||
|
String expected7 = "*" + System.lineSeparator()
|
||||||
|
+ "**" + System.lineSeparator()
|
||||||
|
+ "***" + System.lineSeparator()
|
||||||
|
+ "****" + System.lineSeparator()
|
||||||
|
+ "*****" + System.lineSeparator()
|
||||||
|
+ "******" + System.lineSeparator()
|
||||||
|
+ "*******" + System.lineSeparator();
|
||||||
|
|
||||||
|
return new Object[][] {
|
||||||
|
{ 0, expected0 },
|
||||||
|
{ 2, expected2 },
|
||||||
|
{ 5, expected5 },
|
||||||
|
{ 7, expected7 }
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@Parameters(method = "rightAngledTriangles")
|
||||||
|
public void whenPrintARightAngledTriangleIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) {
|
||||||
|
String actual = PrintTriangleExamples.printARightAngledTriangle(nrOfRows);
|
||||||
|
|
||||||
|
assertEquals(expected, actual);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Object[][] isoscelesTriangles() {
|
||||||
|
String expected0 = "";
|
||||||
|
|
||||||
|
String expected2 = " *" + System.lineSeparator()
|
||||||
|
+ "***" + System.lineSeparator();
|
||||||
|
|
||||||
|
String expected5 = " *" + System.lineSeparator()
|
||||||
|
+ " ***" + System.lineSeparator()
|
||||||
|
+ " *****" + System.lineSeparator()
|
||||||
|
+ " *******" + System.lineSeparator()
|
||||||
|
+ "*********" + System.lineSeparator();
|
||||||
|
|
||||||
|
String expected7 = " *" + System.lineSeparator()
|
||||||
|
+ " ***" + System.lineSeparator()
|
||||||
|
+ " *****" + System.lineSeparator()
|
||||||
|
+ " *******" + System.lineSeparator()
|
||||||
|
+ " *********" + System.lineSeparator()
|
||||||
|
+ " ***********" + System.lineSeparator()
|
||||||
|
+ "*************" + System.lineSeparator();
|
||||||
|
|
||||||
|
return new Object[][] {
|
||||||
|
{ 0, expected0 },
|
||||||
|
{ 2, expected2 },
|
||||||
|
{ 5, expected5 },
|
||||||
|
{ 7, expected7 }
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@Parameters(method = "isoscelesTriangles")
|
||||||
|
public void whenPrintAnIsoscelesTriangleIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) {
|
||||||
|
String actual = PrintTriangleExamples.printAnIsoscelesTriangle(nrOfRows);
|
||||||
|
|
||||||
|
assertEquals(expected, actual);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@Parameters(method = "isoscelesTriangles")
|
||||||
|
public void whenPrintAnIsoscelesTriangleUsingSubstringIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) {
|
||||||
|
String actual = PrintTriangleExamples.printAnIsoscelesTriangleUsingSubstring(nrOfRows);
|
||||||
|
|
||||||
|
assertEquals(expected, actual);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,79 @@
|
|||||||
|
package com.baeldung.algorithms.stringsortingbynumber;
|
||||||
|
|
||||||
|
import com.baeldung.algorithms.stringsortingbynumber.NaturalOrderComparators;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
|
public class NaturalOrderComparatorsUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSimpleStringsContainingIntsAndDoubles_whenSortedByRegex_checkSortingCorrect() {
|
||||||
|
|
||||||
|
List<String> testStrings = Arrays.asList("a1", "b3", "c4", "d2.2", "d2.4", "d2.3d");
|
||||||
|
|
||||||
|
testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator());
|
||||||
|
|
||||||
|
List<String> expected = Arrays.asList("a1", "d2.2", "d2.3d", "d2.4", "b3", "c4");
|
||||||
|
|
||||||
|
assertEquals(expected, testStrings);
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSimpleStringsContainingIntsAndDoublesWithAnInvalidNumber_whenSortedByRegex_checkSortingCorrect() {
|
||||||
|
|
||||||
|
List<String> testStrings = Arrays.asList("a1", "b3", "c4", "d2.2", "d2.4", "d2.3.3d");
|
||||||
|
|
||||||
|
testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator());
|
||||||
|
|
||||||
|
List<String> expected = Arrays.asList("d2.3.3d", "a1", "d2.2", "d2.4", "b3", "c4");
|
||||||
|
|
||||||
|
assertEquals(expected, testStrings);
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAllForseenProblems_whenSortedByRegex_checkSortingCorrect() {
|
||||||
|
|
||||||
|
List<String> testStrings = Arrays.asList("a1", "b3", "c4", "d2.2", "d2.f4", "d2.3.3d");
|
||||||
|
|
||||||
|
testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator());
|
||||||
|
|
||||||
|
List<String> expected = Arrays.asList("d2.3.3d", "a1", "d2.2", "d2.f4", "b3", "c4");
|
||||||
|
|
||||||
|
assertEquals(expected, testStrings);
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenComplexStringsContainingSeparatedNumbers_whenSortedByRegex_checkNumbersCondensedAndSorted() {
|
||||||
|
|
||||||
|
List<String> testStrings = Arrays.asList("a1b2c5", "b3ght3.2", "something65.thensomething5"); //125, 33.2, 65.5
|
||||||
|
|
||||||
|
List<String> expected = Arrays.asList("b3ght3.2", "something65.thensomething5", "a1b2c5" );
|
||||||
|
|
||||||
|
testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator());
|
||||||
|
|
||||||
|
assertEquals(expected, testStrings);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenStringsNotContainingNumbers_whenSortedByRegex_checkOrderNotChanged() {
|
||||||
|
|
||||||
|
List<String> testStrings = Arrays.asList("a", "c", "d", "e");
|
||||||
|
List<String> expected = new ArrayList<>(testStrings);
|
||||||
|
|
||||||
|
testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator());
|
||||||
|
|
||||||
|
assertEquals(expected, testStrings);
|
||||||
|
}
|
||||||
|
}
|
@ -5,3 +5,4 @@
|
|||||||
- [Quicksort Algorithm Implementation in Java](https://www.baeldung.com/java-quicksort)
|
- [Quicksort Algorithm Implementation in Java](https://www.baeldung.com/java-quicksort)
|
||||||
- [Insertion Sort in Java](https://www.baeldung.com/java-insertion-sort)
|
- [Insertion Sort in Java](https://www.baeldung.com/java-insertion-sort)
|
||||||
- [Heap Sort in Java](https://www.baeldung.com/java-heap-sort)
|
- [Heap Sort in Java](https://www.baeldung.com/java-heap-sort)
|
||||||
|
- [Shell Sort in Java](https://www.baeldung.com/java-shell-sort)
|
||||||
|
@ -0,0 +1,25 @@
|
|||||||
|
package com.baeldung.algorithms.inoutsort;
|
||||||
|
|
||||||
|
public class InOutSort {
|
||||||
|
|
||||||
|
public static int[] reverseInPlace(int A[]) {
|
||||||
|
int n = A.length;
|
||||||
|
for (int i = 0; i < n / 2; i++) {
|
||||||
|
int temp = A[i];
|
||||||
|
A[i] = A[n - 1 - i];
|
||||||
|
A[n - 1 - i] = temp;
|
||||||
|
}
|
||||||
|
|
||||||
|
return A;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int[] reverseOutOfPlace(int A[]) {
|
||||||
|
int n = A.length;
|
||||||
|
int[] B = new int[n];
|
||||||
|
for (int i = 0; i < n; i++) {
|
||||||
|
B[n - i - 1] = A[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
return B;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,38 @@
|
|||||||
|
package com.baeldung.algorithms.selectionsort;
|
||||||
|
|
||||||
|
public class SelectionSort {
|
||||||
|
|
||||||
|
public static void sortAscending(final int[] arr) {
|
||||||
|
for (int i = 0; i < arr.length - 1; i++) {
|
||||||
|
int minElementIndex = i;
|
||||||
|
for (int j = i + 1; j < arr.length; j++) {
|
||||||
|
if (arr[minElementIndex] > arr[j]) {
|
||||||
|
minElementIndex = j;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (minElementIndex != i) {
|
||||||
|
int temp = arr[i];
|
||||||
|
arr[i] = arr[minElementIndex];
|
||||||
|
arr[minElementIndex] = temp;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void sortDescending(final int[] arr) {
|
||||||
|
for (int i = 0; i < arr.length - 1; i++) {
|
||||||
|
int maxElementIndex = i;
|
||||||
|
for (int j = i + 1; j < arr.length; j++) {
|
||||||
|
if (arr[maxElementIndex] < arr[j]) {
|
||||||
|
maxElementIndex = j;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (maxElementIndex != i) {
|
||||||
|
int temp = arr[i];
|
||||||
|
arr[i] = arr[maxElementIndex];
|
||||||
|
arr[maxElementIndex] = temp;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,20 @@
|
|||||||
|
package com.baeldung.algorithms.shellsort;
|
||||||
|
|
||||||
|
public class ShellSort {
|
||||||
|
|
||||||
|
public static void sort(int arrayToSort[]) {
|
||||||
|
int n = arrayToSort.length;
|
||||||
|
|
||||||
|
for (int gap = n / 2; gap > 0; gap /= 2) {
|
||||||
|
for (int i = gap; i < n; i++) {
|
||||||
|
int key = arrayToSort[i];
|
||||||
|
int j = i;
|
||||||
|
while (j >= gap && arrayToSort[j - gap] > key) {
|
||||||
|
arrayToSort[j] = arrayToSort[j - gap];
|
||||||
|
j -= gap;
|
||||||
|
}
|
||||||
|
arrayToSort[j] = key;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,23 @@
|
|||||||
|
package com.baeldung.algorithms.inoutsort;
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
import static org.junit.Assert.assertArrayEquals;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class InOutSortUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenArray_whenInPlaceSort_thenReversed() {
|
||||||
|
int[] input = {1, 2, 3, 4, 5, 6, 7};
|
||||||
|
int[] expected = {7, 6, 5, 4, 3, 2, 1};
|
||||||
|
assertArrayEquals("the two arrays are not equal", expected, InOutSort.reverseInPlace(input));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenArray_whenOutOfPlaceSort_thenReversed() {
|
||||||
|
int[] input = {1, 2, 3, 4, 5, 6, 7};
|
||||||
|
int[] expected = {7, 6, 5, 4, 3, 2, 1};
|
||||||
|
assertArrayEquals("the two arrays are not equal", expected, InOutSort.reverseOutOfPlace(input));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,25 @@
|
|||||||
|
package com.baeldung.algorithms.selectionsort;
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
import static org.junit.Assert.assertArrayEquals;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class SelectionSortUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUnsortedArray_whenSelectionSort_SortAscending_thenSortedAsc() {
|
||||||
|
int[] input = { 5, 4, 1, 6, 2 };
|
||||||
|
SelectionSort.sortAscending(input);
|
||||||
|
int[] expected = {1, 2, 4, 5, 6};
|
||||||
|
assertArrayEquals("the two arrays are not equal", expected, input);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUnsortedArray_whenSelectionSort_SortDescending_thenSortedDesc() {
|
||||||
|
int[] input = { 5, 4, 1, 6, 2 };
|
||||||
|
SelectionSort.sortDescending(input);
|
||||||
|
int[] expected = {6, 5, 4, 2, 1};
|
||||||
|
assertArrayEquals("the two arrays are not equal", expected, input);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,17 @@
|
|||||||
|
package com.baeldung.algorithms.shellsort;
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
import static org.junit.Assert.assertArrayEquals;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class ShellSortUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUnsortedArray_whenShellSort_thenSortedAsc() {
|
||||||
|
int[] input = {41, 15, 82, 5, 65, 19, 32, 43, 8};
|
||||||
|
ShellSort.sort(input);
|
||||||
|
int[] expected = {5, 8, 15, 19, 32, 41, 43, 65, 82};
|
||||||
|
assertArrayEquals("the two arrays are not equal", expected, input);
|
||||||
|
}
|
||||||
|
}
|
@ -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)
|
||||||
|
@ -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>
|
||||||
|
@ -18,12 +18,6 @@
|
|||||||
<groupId>org.axonframework</groupId>
|
<groupId>org.axonframework</groupId>
|
||||||
<artifactId>axon-spring-boot-starter</artifactId>
|
<artifactId>axon-spring-boot-starter</artifactId>
|
||||||
<version>${axon.version}</version>
|
<version>${axon.version}</version>
|
||||||
<exclusions>
|
|
||||||
<exclusion>
|
|
||||||
<groupId>org.axonframework</groupId>
|
|
||||||
<artifactId>axon-server-connector</artifactId>
|
|
||||||
</exclusion>
|
|
||||||
</exclusions>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
@ -58,7 +52,7 @@
|
|||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<axon.version>4.0.3</axon.version>
|
<axon.version>4.1.2</axon.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -13,6 +13,7 @@ import com.baeldung.axon.coreapi.commands.ShipOrderCommand;
|
|||||||
import com.baeldung.axon.coreapi.events.OrderConfirmedEvent;
|
import com.baeldung.axon.coreapi.events.OrderConfirmedEvent;
|
||||||
import com.baeldung.axon.coreapi.events.OrderPlacedEvent;
|
import com.baeldung.axon.coreapi.events.OrderPlacedEvent;
|
||||||
import com.baeldung.axon.coreapi.events.OrderShippedEvent;
|
import com.baeldung.axon.coreapi.events.OrderShippedEvent;
|
||||||
|
import com.baeldung.axon.coreapi.exceptions.UnconfirmedOrderException;
|
||||||
|
|
||||||
@Aggregate
|
@Aggregate
|
||||||
public class OrderAggregate {
|
public class OrderAggregate {
|
||||||
@ -34,7 +35,7 @@ public class OrderAggregate {
|
|||||||
@CommandHandler
|
@CommandHandler
|
||||||
public void handle(ShipOrderCommand command) {
|
public void handle(ShipOrderCommand command) {
|
||||||
if (!orderConfirmed) {
|
if (!orderConfirmed) {
|
||||||
throw new IllegalStateException("Cannot ship an order which has not been confirmed yet.");
|
throw new UnconfirmedOrderException();
|
||||||
}
|
}
|
||||||
|
|
||||||
apply(new OrderShippedEvent(orderId));
|
apply(new OrderShippedEvent(orderId));
|
||||||
@ -43,12 +44,12 @@ public class OrderAggregate {
|
|||||||
@EventSourcingHandler
|
@EventSourcingHandler
|
||||||
public void on(OrderPlacedEvent event) {
|
public void on(OrderPlacedEvent event) {
|
||||||
this.orderId = event.getOrderId();
|
this.orderId = event.getOrderId();
|
||||||
orderConfirmed = false;
|
this.orderConfirmed = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@EventSourcingHandler
|
@EventSourcingHandler
|
||||||
public void on(OrderConfirmedEvent event) {
|
public void on(OrderConfirmedEvent event) {
|
||||||
orderConfirmed = true;
|
this.orderConfirmed = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected OrderAggregate() {
|
protected OrderAggregate() {
|
||||||
|
@ -0,0 +1,8 @@
|
|||||||
|
package com.baeldung.axon.coreapi.exceptions;
|
||||||
|
|
||||||
|
public class UnconfirmedOrderException extends IllegalStateException {
|
||||||
|
|
||||||
|
public UnconfirmedOrderException() {
|
||||||
|
super("Cannot ship an order which has not been confirmed yet.");
|
||||||
|
}
|
||||||
|
}
|
@ -5,6 +5,7 @@ import java.util.HashMap;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.axonframework.config.ProcessingGroup;
|
||||||
import org.axonframework.eventhandling.EventHandler;
|
import org.axonframework.eventhandling.EventHandler;
|
||||||
import org.axonframework.queryhandling.QueryHandler;
|
import org.axonframework.queryhandling.QueryHandler;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
@ -16,6 +17,7 @@ import com.baeldung.axon.coreapi.queries.FindAllOrderedProductsQuery;
|
|||||||
import com.baeldung.axon.coreapi.queries.OrderedProduct;
|
import com.baeldung.axon.coreapi.queries.OrderedProduct;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
|
@ProcessingGroup("ordered-products")
|
||||||
public class OrderedProductsEventHandler {
|
public class OrderedProductsEventHandler {
|
||||||
|
|
||||||
private final Map<String, OrderedProduct> orderedProducts = new HashMap<>();
|
private final Map<String, OrderedProduct> orderedProducts = new HashMap<>();
|
||||||
|
1
axon/src/main/resources/application.properties
Normal file
1
axon/src/main/resources/application.properties
Normal file
@ -0,0 +1 @@
|
|||||||
|
spring.application.name=Order Management Service
|
@ -2,6 +2,7 @@ package com.baeldung.axon.commandmodel;
|
|||||||
|
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
|
import com.baeldung.axon.coreapi.exceptions.UnconfirmedOrderException;
|
||||||
import org.axonframework.test.aggregate.AggregateTestFixture;
|
import org.axonframework.test.aggregate.AggregateTestFixture;
|
||||||
import org.axonframework.test.aggregate.FixtureConfiguration;
|
import org.axonframework.test.aggregate.FixtureConfiguration;
|
||||||
import org.junit.*;
|
import org.junit.*;
|
||||||
@ -41,12 +42,12 @@ public class OrderAggregateUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenOrderPlacedEvent_whenShipOrderCommand_thenShouldThrowIllegalStateException() {
|
public void givenOrderPlacedEvent_whenShipOrderCommand_thenShouldThrowUnconfirmedOrderException() {
|
||||||
String orderId = UUID.randomUUID().toString();
|
String orderId = UUID.randomUUID().toString();
|
||||||
String product = "Deluxe Chair";
|
String product = "Deluxe Chair";
|
||||||
fixture.given(new OrderPlacedEvent(orderId, product))
|
fixture.given(new OrderPlacedEvent(orderId, product))
|
||||||
.when(new ShipOrderCommand(orderId))
|
.when(new ShipOrderCommand(orderId))
|
||||||
.expectException(IllegalStateException.class);
|
.expectException(UnconfirmedOrderException.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -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>
|
||||||
|
|
||||||
|
@ -6,3 +6,6 @@
|
|||||||
- [Template Engines in Groovy](https://www.baeldung.com/groovy-template-engines)
|
- [Template Engines in Groovy](https://www.baeldung.com/groovy-template-engines)
|
||||||
- [Groovy def Keyword](https://www.baeldung.com/groovy-def-keyword)
|
- [Groovy def Keyword](https://www.baeldung.com/groovy-def-keyword)
|
||||||
- [Pattern Matching in Strings in Groovy](https://www.baeldung.com/groovy-pattern-matching)
|
- [Pattern Matching in Strings in Groovy](https://www.baeldung.com/groovy-pattern-matching)
|
||||||
|
- [Working with XML in Groovy](https://www.baeldung.com/groovy-xml)
|
||||||
|
- [Integrating Groovy into Java Applications](https://www.baeldung.com/groovy-java-applications)
|
||||||
|
- [Concatenate Strings with Groovy](https://www.baeldung.com/groovy-concatenate-strings)
|
||||||
|
@ -171,13 +171,10 @@
|
|||||||
</pluginRepository>
|
</pluginRepository>
|
||||||
</pluginRepositories>
|
</pluginRepositories>
|
||||||
|
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<junit.platform.version>1.0.0</junit.platform.version>
|
<junit.platform.version>1.0.0</junit.platform.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>
|
||||||
<commons-lang3.version>3.9</commons-lang3.version>
|
|
||||||
<java.version>1.8</java.version>
|
|
||||||
<maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
|
<maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
|
||||||
<logback.version>1.2.3</logback.version>
|
<logback.version>1.2.3</logback.version>
|
||||||
<groovy.version>2.5.7</groovy.version>
|
<groovy.version>2.5.7</groovy.version>
|
||||||
|
@ -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,45 @@
|
|||||||
|
package com.baeldung.metaprogramming
|
||||||
|
|
||||||
|
import groovy.transform.AutoClone
|
||||||
|
import groovy.transform.Canonical
|
||||||
|
import groovy.transform.EqualsAndHashCode
|
||||||
|
import groovy.transform.ToString
|
||||||
|
import groovy.transform.TupleConstructor
|
||||||
|
import groovy.util.logging.*
|
||||||
|
|
||||||
|
@Canonical
|
||||||
|
@TupleConstructor
|
||||||
|
@EqualsAndHashCode
|
||||||
|
@ToString(includePackage=false, excludes=['id'])
|
||||||
|
@Log
|
||||||
|
@AutoClone
|
||||||
|
class Employee {
|
||||||
|
|
||||||
|
long id
|
||||||
|
String firstName
|
||||||
|
String lastName
|
||||||
|
int age
|
||||||
|
|
||||||
|
//method to catch missing property's getter
|
||||||
|
def propertyMissing(String propertyName) {
|
||||||
|
log.info "$propertyName is not available"
|
||||||
|
"property '$propertyName' is not available"
|
||||||
|
}
|
||||||
|
|
||||||
|
//method to catch missing property's setter
|
||||||
|
def propertyMissing(String propertyName, propertyValue) {
|
||||||
|
println "property '$propertyName' is not available"
|
||||||
|
log.info "$propertyName is not available"
|
||||||
|
"property '$propertyName' is not available"
|
||||||
|
}
|
||||||
|
|
||||||
|
def methodMissing(String methodName, def methodArgs) {
|
||||||
|
log.info "$methodName is not defined"
|
||||||
|
"method '$methodName' is not defined"
|
||||||
|
}
|
||||||
|
|
||||||
|
def logEmp() {
|
||||||
|
log.info "Employee: $lastName, $firstName is of $age years age"
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,30 @@
|
|||||||
|
package com.baeldung.metaprogramming.extension
|
||||||
|
|
||||||
|
import com.baeldung.metaprogramming.Employee
|
||||||
|
|
||||||
|
class BasicExtensions {
|
||||||
|
|
||||||
|
static int getYearOfBirth(Employee self) {
|
||||||
|
return (new Date().getYear() + 1900) - self.age;
|
||||||
|
}
|
||||||
|
|
||||||
|
static String capitalize(String self) {
|
||||||
|
return self.substring(0, 1).toUpperCase() + self.substring(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
static void printCounter(Integer self) {
|
||||||
|
while (self>0) {
|
||||||
|
println self
|
||||||
|
self--
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static Long square(Long self) {
|
||||||
|
return self*self
|
||||||
|
}
|
||||||
|
|
||||||
|
static BigDecimal cube(BigDecimal self) {
|
||||||
|
return self*self*self
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,10 @@
|
|||||||
|
package com.baeldung.metaprogramming.extension
|
||||||
|
|
||||||
|
import com.baeldung.metaprogramming.Employee
|
||||||
|
|
||||||
|
class StaticEmployeeExtension {
|
||||||
|
|
||||||
|
static Employee getDefaultObj(Employee self) {
|
||||||
|
return new Employee(firstName: "firstName", lastName: "lastName", age: 20)
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,4 @@
|
|||||||
|
moduleName=core-groovy-2
|
||||||
|
moduleVersion=1.0-SNAPSHOT
|
||||||
|
extensionClasses=com.baeldung.metaprogramming.extension.BasicExtensions
|
||||||
|
staticExtensionClasses=com.baeldung.metaprogramming.extension.StaticEmployeeExtension
|
@ -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,118 @@
|
|||||||
|
package com.baeldung.metaprogramming
|
||||||
|
|
||||||
|
import groovy.time.TimeCategory
|
||||||
|
|
||||||
|
class MetaprogrammingUnitTest extends GroovyTestCase {
|
||||||
|
|
||||||
|
Employee emp = new Employee(firstName: "Norman", lastName: "Lewis")
|
||||||
|
|
||||||
|
void testPropertyMissing() {
|
||||||
|
assert emp.address == "property 'address' is not available"
|
||||||
|
}
|
||||||
|
|
||||||
|
void testMethodMissing() {
|
||||||
|
Employee emp = new Employee()
|
||||||
|
try {
|
||||||
|
emp.getFullName()
|
||||||
|
} catch(MissingMethodException e) {
|
||||||
|
println "method is not defined"
|
||||||
|
}
|
||||||
|
assert emp.getFullName() == "method 'getFullName' is not defined"
|
||||||
|
}
|
||||||
|
|
||||||
|
void testMetaClassProperty() {
|
||||||
|
Employee.metaClass.address = ""
|
||||||
|
emp = new Employee(firstName: "Norman", lastName: "Lewis", address: "US")
|
||||||
|
assert emp.address == "US"
|
||||||
|
}
|
||||||
|
|
||||||
|
void testMetaClassMethod() {
|
||||||
|
emp.metaClass.getFullName = {
|
||||||
|
"$lastName, $firstName"
|
||||||
|
}
|
||||||
|
assert emp.getFullName() == "Lewis, Norman"
|
||||||
|
}
|
||||||
|
|
||||||
|
void testMetaClassConstructor() {
|
||||||
|
try {
|
||||||
|
Employee emp = new Employee("Norman")
|
||||||
|
} catch(GroovyRuntimeException e) {
|
||||||
|
assert e.message == "Could not find matching constructor for: com.baeldung.metaprogramming.Employee(String)"
|
||||||
|
}
|
||||||
|
|
||||||
|
Employee.metaClass.constructor = { String firstName ->
|
||||||
|
new Employee(firstName: firstName)
|
||||||
|
}
|
||||||
|
|
||||||
|
Employee norman = new Employee("Norman")
|
||||||
|
assert norman.firstName == "Norman"
|
||||||
|
assert norman.lastName == null
|
||||||
|
}
|
||||||
|
|
||||||
|
void testJavaMetaClass() {
|
||||||
|
String.metaClass.capitalize = { String str ->
|
||||||
|
str.substring(0, 1).toUpperCase() + str.substring(1);
|
||||||
|
}
|
||||||
|
assert "norman".capitalize() == "Norman"
|
||||||
|
}
|
||||||
|
|
||||||
|
void testEmployeeExtension() {
|
||||||
|
Employee emp = new Employee(age: 28)
|
||||||
|
assert emp.getYearOfBirth() == 1991
|
||||||
|
}
|
||||||
|
|
||||||
|
void testJavaClassesExtensions() {
|
||||||
|
5.printCounter()
|
||||||
|
|
||||||
|
assert 40l.square() == 1600l
|
||||||
|
|
||||||
|
assert (2.98).cube() == 26.463592
|
||||||
|
}
|
||||||
|
|
||||||
|
void testStaticEmployeeExtension() {
|
||||||
|
assert Employee.getDefaultObj().firstName == "firstName"
|
||||||
|
assert Employee.getDefaultObj().lastName == "lastName"
|
||||||
|
assert Employee.getDefaultObj().age == 20
|
||||||
|
}
|
||||||
|
|
||||||
|
void testToStringAnnotation() {
|
||||||
|
Employee employee = new Employee()
|
||||||
|
employee.id = 1
|
||||||
|
employee.firstName = "norman"
|
||||||
|
employee.lastName = "lewis"
|
||||||
|
employee.age = 28
|
||||||
|
|
||||||
|
assert employee.toString() == "Employee(norman, lewis, 28)"
|
||||||
|
}
|
||||||
|
|
||||||
|
void testTupleConstructorAnnotation() {
|
||||||
|
Employee norman = new Employee(1, "norman", "lewis", 28)
|
||||||
|
assert norman.toString() == "Employee(norman, lewis, 28)"
|
||||||
|
|
||||||
|
Employee snape = new Employee(2, "snape")
|
||||||
|
assert snape.toString() == "Employee(snape, null, 0)"
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
void testEqualsAndHashCodeAnnotation() {
|
||||||
|
Employee norman = new Employee(1, "norman", "lewis", 28)
|
||||||
|
Employee normanCopy = new Employee(1, "norman", "lewis", 28)
|
||||||
|
assert norman.equals(normanCopy)
|
||||||
|
assert norman.hashCode() == normanCopy.hashCode()
|
||||||
|
}
|
||||||
|
|
||||||
|
void testAutoCloneAnnotation() {
|
||||||
|
try {
|
||||||
|
Employee norman = new Employee(1, "norman", "lewis", 28)
|
||||||
|
def normanCopy = norman.clone()
|
||||||
|
assert norman == normanCopy
|
||||||
|
} catch(CloneNotSupportedException e) {
|
||||||
|
e.printStackTrace()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void testLoggingAnnotation() {
|
||||||
|
Employee employee = new Employee(1, "Norman", "Lewis", 28)
|
||||||
|
employee.logEmp()
|
||||||
|
}
|
||||||
|
}
|
@ -1,3 +0,0 @@
|
|||||||
## Relevant Articles
|
|
||||||
|
|
||||||
- [Extending an Array’s Length](https://www.baeldung.com/java-array-add-element-at-the-end)
|
|
@ -3,3 +3,4 @@
|
|||||||
- [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)
|
- [Guide to Java FileChannel](https://www.baeldung.com/java-filechannel)
|
||||||
- [Understanding the NumberFormatException in Java](https://www.baeldung.com/java-number-format-exception)
|
- [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,3 @@
|
|||||||
|
## Relevant articles:
|
||||||
|
|
||||||
|
- [Negate a Predicate Method Reference with Java 11](https://www.baeldung.com/java-negate-predicate-method-reference)
|
4
core-java-modules/core-java-12/README.md
Normal file
4
core-java-modules/core-java-12/README.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
## Relevant Articles:
|
||||||
|
|
||||||
|
|
||||||
|
- [String API Updates in Java 12](https://www.baeldung.com/java12-string-api)
|
@ -6,3 +6,5 @@
|
|||||||
- [Anonymous Classes in Java](http://www.baeldung.com/)
|
- [Anonymous Classes in Java](http://www.baeldung.com/)
|
||||||
- [How to Delay Code Execution in Java](https://www.baeldung.com/java-delay-code-execution)
|
- [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)
|
||||||
|
- [Guide to Java BiFunction Interface](https://www.baeldung.com/java-bifunction-interface)
|
||||||
|
@ -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,19 +16,18 @@
|
|||||||
<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>
|
|
||||||
</properties>
|
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.ibm.icu</groupId>
|
<groupId>com.ibm.icu</groupId>
|
||||||
<artifactId>icu4j</artifactId>
|
<artifactId>icu4j</artifactId>
|
||||||
<version>${icu.version}</version>
|
<version>${icu.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.assertj</groupId>
|
||||||
|
<artifactId>assertj-core</artifactId>
|
||||||
|
<version>${assertj.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
@ -44,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,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);
|
||||||
|
}
|
||||||
|
}
|
@ -4,14 +4,10 @@
|
|||||||
|
|
||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
- [Guide to Java 8’s Collectors](http://www.baeldung.com/java-8-collectors)
|
- [Guide to Java 8’s Collectors](http://www.baeldung.com/java-8-collectors)
|
||||||
- [Functional Interfaces in Java 8](http://www.baeldung.com/java-8-functional-interfaces)
|
|
||||||
- [Java 8 – Powerful Comparison with Lambdas](http://www.baeldung.com/java-8-sort-lambda)
|
|
||||||
- [New Features in Java 8](http://www.baeldung.com/java-8-new-features)
|
- [New Features in Java 8](http://www.baeldung.com/java-8-new-features)
|
||||||
- [Lambda Expressions and Functional Interfaces: Tips and Best Practices](http://www.baeldung.com/java-8-lambda-expressions-tips)
|
|
||||||
- [The Double Colon Operator in Java 8](http://www.baeldung.com/java-8-double-colon-operator)
|
- [The Double Colon Operator in Java 8](http://www.baeldung.com/java-8-double-colon-operator)
|
||||||
- [Guide to Java 8 groupingBy Collector](http://www.baeldung.com/java-groupingby-collector)
|
- [Guide to Java 8 groupingBy Collector](http://www.baeldung.com/java-groupingby-collector)
|
||||||
- [Strategy Design Pattern in Java 8](http://www.baeldung.com/java-strategy-pattern)
|
- [Strategy Design Pattern in Java 8](http://www.baeldung.com/java-strategy-pattern)
|
||||||
- [Exceptions in Java 8 Lambda Expressions](http://www.baeldung.com/java-lambda-exceptions)
|
|
||||||
- [Guide to Java 8 Comparator.comparing()](http://www.baeldung.com/java-8-comparator-comparing)
|
- [Guide to Java 8 Comparator.comparing()](http://www.baeldung.com/java-8-comparator-comparing)
|
||||||
- [Guide To Java 8 Optional](http://www.baeldung.com/java-optional)
|
- [Guide To Java 8 Optional](http://www.baeldung.com/java-optional)
|
||||||
- [Guide to the Java 8 forEach](http://www.baeldung.com/foreach-java)
|
- [Guide to the Java 8 forEach](http://www.baeldung.com/foreach-java)
|
||||||
@ -38,5 +34,5 @@
|
|||||||
- [Java @SafeVarargs Annotation](https://www.baeldung.com/java-safevarargs)
|
- [Java @SafeVarargs Annotation](https://www.baeldung.com/java-safevarargs)
|
||||||
- [Java @Deprecated Annotation](https://www.baeldung.com/java-deprecated)
|
- [Java @Deprecated Annotation](https://www.baeldung.com/java-deprecated)
|
||||||
- [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)
|
|
||||||
- [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());
|
||||||
|
// }
|
||||||
|
|
||||||
}
|
}
|
25
core-java-modules/core-java-arrays-2/.gitignore
vendored
Normal file
25
core-java-modules/core-java-arrays-2/.gitignore
vendored
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
*.class
|
||||||
|
|
||||||
|
0.*
|
||||||
|
|
||||||
|
#folders#
|
||||||
|
/target
|
||||||
|
/neoDb*
|
||||||
|
/data
|
||||||
|
/src/main/webapp/WEB-INF/classes
|
||||||
|
*/META-INF/*
|
||||||
|
.resourceCache
|
||||||
|
|
||||||
|
# Packaged files #
|
||||||
|
*.jar
|
||||||
|
*.war
|
||||||
|
*.ear
|
||||||
|
|
||||||
|
# Files generated by integration tests
|
||||||
|
backup-pom.xml
|
||||||
|
/bin/
|
||||||
|
/temp
|
||||||
|
|
||||||
|
#IntelliJ specific
|
||||||
|
.idea/
|
||||||
|
*.iml
|
5
core-java-modules/core-java-arrays-2/README.MD
Normal file
5
core-java-modules/core-java-arrays-2/README.MD
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
## Relevant Articles
|
||||||
|
|
||||||
|
- [Extending an Array’s Length](https://www.baeldung.com/java-array-add-element-at-the-end)
|
||||||
|
- [Checking If an Array Is Sorted in Java](https://www.baeldung.com/java-check-sorted-array)
|
||||||
|
- [Looping Diagonally Through a 2d Java Array](https://www.baeldung.com/java-loop-diagonal-array)
|
50
core-java-modules/core-java-arrays-2/pom.xml
Normal file
50
core-java-modules/core-java-arrays-2/pom.xml
Normal file
@ -0,0 +1,50 @@
|
|||||||
|
<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>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>core-java-arrays-2</artifactId>
|
||||||
|
<version>0.1.0-SNAPSHOT</version>
|
||||||
|
<name>core-java-arrays-2</name>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>parent-java</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
<relativePath>../../parent-java</relativePath>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.commons</groupId>
|
||||||
|
<artifactId>commons-lang3</artifactId>
|
||||||
|
<version>${commons-lang3.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<!-- test scoped -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.assertj</groupId>
|
||||||
|
<artifactId>assertj-core</artifactId>
|
||||||
|
<version>${assertj-core.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<finalName>core-java-arrays-2</finalName>
|
||||||
|
<resources>
|
||||||
|
<resource>
|
||||||
|
<directory>src/main/resources</directory>
|
||||||
|
<filtering>true</filtering>
|
||||||
|
</resource>
|
||||||
|
</resources>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
|
||||||
|
<!-- util -->
|
||||||
|
<commons-lang3.version>3.9</commons-lang3.version>
|
||||||
|
<!-- testing -->
|
||||||
|
<assertj-core.version>3.10.0</assertj-core.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
</project>
|
@ -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 LoopDiagonallyUnitTest {
|
||||||
|
|
||||||
|
@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);
|
||||||
|
}
|
||||||
|
}
|
@ -7,7 +7,7 @@
|
|||||||
- [Check if a Java Array Contains a Value](http://www.baeldung.com/java-array-contains-value)
|
- [Check if a Java Array Contains a Value](http://www.baeldung.com/java-array-contains-value)
|
||||||
- [Initializing Arrays in Java](http://www.baeldung.com/java-initialize-array)
|
- [Initializing Arrays in Java](http://www.baeldung.com/java-initialize-array)
|
||||||
- [Guide to the java.util.Arrays Class](http://www.baeldung.com/java-util-arrays)
|
- [Guide to the java.util.Arrays Class](http://www.baeldung.com/java-util-arrays)
|
||||||
- [Jagged Arrays In Java](http://www.baeldung.com/java-jagged-arrays)
|
- [Multi-Dimensional Arrays In Java](http://www.baeldung.com/java-jagged-arrays)
|
||||||
- [Find Sum and Average in a Java Array](http://www.baeldung.com/java-array-sum-average)
|
- [Find Sum and Average in a Java Array](http://www.baeldung.com/java-array-sum-average)
|
||||||
- [Arrays in Java: A Reference Guide](https://www.baeldung.com/java-arrays-guide)
|
- [Arrays in Java: A Reference Guide](https://www.baeldung.com/java-arrays-guide)
|
||||||
- [How to Invert an Array in Java](http://www.baeldung.com/java-invert-array)
|
- [How to Invert an Array in Java](http://www.baeldung.com/java-invert-array)
|
||||||
@ -16,3 +16,4 @@
|
|||||||
- [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)
|
- [Converting Between Stream and Array in Java](https://www.baeldung.com/java-stream-to-array)
|
||||||
|
- [Removing an Element from an Array in Java](https://www.baeldung.com/java-array-remove-element)
|
||||||
|
@ -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,65 @@
|
|||||||
|
package com.baeldung.array;
|
||||||
|
|
||||||
|
import com.baeldung.arraycopy.model.Employee;
|
||||||
|
|
||||||
|
import java.util.Comparator;
|
||||||
|
|
||||||
|
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(Comparable[] 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(Comparable[] array) {
|
||||||
|
for (int i = 0; i < array.length - 1; ++i) {
|
||||||
|
if (array[i].compareTo(array[i + 1]) > 0)
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean isSorted(Object[] array, Comparator comparator) {
|
||||||
|
for (int i = 0; i < array.length - 1; ++i) {
|
||||||
|
if (comparator.compare(array[i], (array[i + 1])) > 0)
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean isSorted(Object[] array, Comparator comparator, int length) {
|
||||||
|
if (array == null || length < 2)
|
||||||
|
return true;
|
||||||
|
|
||||||
|
if (comparator.compare(array[length - 2], array[length - 1]) > 0)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
return isSorted(array, comparator, 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,79 @@
|
|||||||
|
package com.baeldung.array;
|
||||||
|
|
||||||
|
import com.baeldung.arraycopy.model.Employee;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.Comparator;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
public 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 static final Employee[] EMPLOYEES_SORTED_BY_NAME = {
|
||||||
|
new Employee(1, "Carlos", 26),
|
||||||
|
new Employee(2, "Daniel", 31),
|
||||||
|
new Employee(3, "Marta", 27)};
|
||||||
|
|
||||||
|
private static final Employee[] EMPLOYEES_NOT_SORTED_BY_NAME = {
|
||||||
|
new Employee(1, "Daniel", 31),
|
||||||
|
new Employee(2, "Carlos", 26),
|
||||||
|
new Employee(3, "Marta", 27)};
|
||||||
|
|
||||||
|
private static final Employee[] EMPLOYEES_SORTED_BY_AGE = {
|
||||||
|
new Employee(1, "Carlos", 26),
|
||||||
|
new Employee(2, "Marta", 27),
|
||||||
|
new Employee(3, "Daniel", 31)};
|
||||||
|
|
||||||
|
private static 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.isSorted(EMPLOYEES_SORTED_BY_NAME, Comparator.comparing(Employee::getName))).isEqualTo(true);
|
||||||
|
assertThat(sortedArrayChecker.isSorted(EMPLOYEES_NOT_SORTED_BY_NAME, Comparator.comparing(Employee::getName))).isEqualTo(false);
|
||||||
|
|
||||||
|
assertThat(sortedArrayChecker.isSorted(EMPLOYEES_SORTED_BY_AGE, Comparator.comparingInt(Employee::getAge))).isEqualTo(true);
|
||||||
|
assertThat(sortedArrayChecker.isSorted(EMPLOYEES_NOT_SORTED_BY_AGE, Comparator.comparingInt(Employee::getAge))).isEqualTo(false);
|
||||||
|
|
||||||
|
assertThat(sortedArrayChecker
|
||||||
|
.isSorted(EMPLOYEES_SORTED_BY_AGE, Comparator.comparingInt(Employee::getAge), EMPLOYEES_SORTED_BY_AGE.length))
|
||||||
|
.isEqualTo(true);
|
||||||
|
assertThat(sortedArrayChecker
|
||||||
|
.isSorted(EMPLOYEES_NOT_SORTED_BY_AGE, Comparator.comparingInt(Employee::getAge), 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)
|
||||||
|
@ -27,17 +27,18 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.google.code.gson</groupId>
|
<groupId>com.google.code.gson</groupId>
|
||||||
<artifactId>gson</artifactId>
|
<artifactId>gson</artifactId>
|
||||||
<version>2.8.5</version>
|
<version>${gson.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>commons-lang</groupId>
|
<groupId>commons-lang</groupId>
|
||||||
<artifactId>commons-lang</artifactId>
|
<artifactId>commons-lang</artifactId>
|
||||||
<version>2.6</version>
|
<version>${commons-lang.version}</version>
|
||||||
</dependency>
|
</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>
|
@ -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>
|
||||||
|
@ -0,0 +1,11 @@
|
|||||||
|
package com.baeldung.concurrent.mutex;
|
||||||
|
|
||||||
|
public class SequenceGenerator {
|
||||||
|
private int currentValue = 0;
|
||||||
|
|
||||||
|
public int getNextSequence() throws InterruptedException {
|
||||||
|
currentValue = currentValue + 1;
|
||||||
|
Thread.sleep(500);
|
||||||
|
return currentValue;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,18 @@
|
|||||||
|
package com.baeldung.concurrent.mutex;
|
||||||
|
|
||||||
|
import com.google.common.util.concurrent.Monitor;
|
||||||
|
|
||||||
|
public class SequenceGeneratorUsingMonitor extends SequenceGenerator {
|
||||||
|
|
||||||
|
private Monitor monitor = new Monitor();
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int getNextSequence() throws InterruptedException {
|
||||||
|
monitor.enter();
|
||||||
|
try {
|
||||||
|
return super.getNextSequence();
|
||||||
|
} finally {
|
||||||
|
monitor.leave();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,18 @@
|
|||||||
|
package com.baeldung.concurrent.mutex;
|
||||||
|
|
||||||
|
import java.util.concurrent.locks.ReentrantLock;
|
||||||
|
|
||||||
|
public class SequenceGeneratorUsingReentrantLock extends SequenceGenerator {
|
||||||
|
|
||||||
|
private ReentrantLock mutex = new ReentrantLock();
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int getNextSequence() throws InterruptedException {
|
||||||
|
try {
|
||||||
|
mutex.lock();
|
||||||
|
return super.getNextSequence();
|
||||||
|
} finally {
|
||||||
|
mutex.unlock();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,18 @@
|
|||||||
|
package com.baeldung.concurrent.mutex;
|
||||||
|
|
||||||
|
import java.util.concurrent.Semaphore;
|
||||||
|
|
||||||
|
public class SequenceGeneratorUsingSemaphore extends SequenceGenerator {
|
||||||
|
|
||||||
|
private Semaphore mutex = new Semaphore(1);
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int getNextSequence() throws InterruptedException {
|
||||||
|
try {
|
||||||
|
mutex.acquire();
|
||||||
|
return super.getNextSequence();
|
||||||
|
} finally {
|
||||||
|
mutex.release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,12 @@
|
|||||||
|
package com.baeldung.concurrent.mutex;
|
||||||
|
|
||||||
|
public class SequenceGeneratorUsingSynchronizedBlock extends SequenceGenerator {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int getNextSequence() throws InterruptedException {
|
||||||
|
synchronized (this) {
|
||||||
|
return super.getNextSequence();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,10 @@
|
|||||||
|
package com.baeldung.concurrent.mutex;
|
||||||
|
|
||||||
|
public class SequenceGeneratorUsingSynchronizedMethod extends SequenceGenerator {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public synchronized int getNextSequence() throws InterruptedException {
|
||||||
|
return super.getNextSequence();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user