commit
822473f95d
|
@ -58,7 +58,7 @@ class MetaprogrammingUnitTest extends GroovyTestCase {
|
|||
|
||||
void testEmployeeExtension() {
|
||||
Employee emp = new Employee(age: 28)
|
||||
assert emp.getYearOfBirth() == 1991
|
||||
assert emp.getYearOfBirth() == 1992
|
||||
}
|
||||
|
||||
void testJavaClassesExtensions() {
|
||||
|
@ -115,4 +115,4 @@ class MetaprogrammingUnitTest extends GroovyTestCase {
|
|||
Employee employee = new Employee(1, "Norman", "Lewis", 28)
|
||||
employee.logEmp()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,52 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>core-java-14</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<name>core-java-14</name>
|
||||
<packaging>jar</packaging>
|
||||
<url>http://maven.apache.org</url>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../</relativePath>
|
||||
</parent>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${maven.compiler.source.version}</source>
|
||||
<target>${maven.compiler.target.version}</target>
|
||||
<compilerArgs>
|
||||
<compilerArg>
|
||||
--enable-preview
|
||||
</compilerArg>
|
||||
</compilerArgs>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>3.0.0-M3</version>
|
||||
<configuration>
|
||||
<argLine>--enable-preview</argLine>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source.version>14</maven.compiler.source.version>
|
||||
<maven.compiler.target.version>14</maven.compiler.target.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,50 @@
|
|||
package com.baeldung.serial;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.ObjectInputStream;
|
||||
import java.io.ObjectOutputStream;
|
||||
import java.io.ObjectStreamException;
|
||||
import java.io.ObjectStreamField;
|
||||
import java.io.Serial;
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* Class showcasing the usage of the Java 14 @Serial annotation.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*/
|
||||
public class MySerialClass implements Serializable {
|
||||
|
||||
@Serial
|
||||
private static final ObjectStreamField[] serialPersistentFields = null;
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1;
|
||||
|
||||
@Serial
|
||||
private void writeObject(ObjectOutputStream stream) throws IOException {
|
||||
// ...
|
||||
}
|
||||
|
||||
@Serial
|
||||
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
|
||||
// ...
|
||||
}
|
||||
|
||||
@Serial
|
||||
private void readObjectNoData() throws ObjectStreamException {
|
||||
// ...
|
||||
}
|
||||
|
||||
@Serial
|
||||
private Object writeReplace() throws ObjectStreamException {
|
||||
// ...
|
||||
return null;
|
||||
}
|
||||
|
||||
@Serial
|
||||
private Object readResolve() throws ObjectStreamException {
|
||||
// ...
|
||||
return null;
|
||||
}
|
||||
}
|
|
@ -19,6 +19,16 @@
|
|||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>${jmh.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${jmh.version}</version>
|
||||
</dependency>
|
||||
<!-- test scoped -->
|
||||
<dependency>
|
||||
|
@ -37,9 +47,34 @@
|
|||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<version>3.2.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>shade</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<finalName>benchmarks</finalName>
|
||||
<transformers>
|
||||
<transformer
|
||||
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
|
||||
<mainClass>org.openjdk.jmh.Main</mainClass>
|
||||
</transformer>
|
||||
</transformers>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<jmh.version>1.19</jmh.version>
|
||||
<!-- util -->
|
||||
<commons-lang3.version>3.9</commons-lang3.version>
|
||||
<!-- testing -->
|
||||
|
|
|
@ -0,0 +1,72 @@
|
|||
package com.baeldung.arraysort;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.openjdk.jmh.annotations.Benchmark;
|
||||
import org.openjdk.jmh.annotations.BenchmarkMode;
|
||||
import org.openjdk.jmh.annotations.Fork;
|
||||
import org.openjdk.jmh.annotations.Level;
|
||||
import org.openjdk.jmh.annotations.Measurement;
|
||||
import org.openjdk.jmh.annotations.Mode;
|
||||
import org.openjdk.jmh.annotations.OutputTimeUnit;
|
||||
import org.openjdk.jmh.annotations.Param;
|
||||
import org.openjdk.jmh.annotations.Scope;
|
||||
import org.openjdk.jmh.annotations.Setup;
|
||||
import org.openjdk.jmh.annotations.State;
|
||||
import org.openjdk.jmh.annotations.Warmup;
|
||||
import org.openjdk.jmh.infra.Blackhole;
|
||||
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@Warmup(iterations = 5)
|
||||
@Measurement(iterations = 10)
|
||||
@Fork(2)
|
||||
@OutputTimeUnit(TimeUnit.MILLISECONDS)
|
||||
public class ArraySortingBenchmark {
|
||||
|
||||
@State(Scope.Benchmark)
|
||||
public static class ArrayContainer {
|
||||
|
||||
@Param({ "1000", "10000", "100000", "1000000" })
|
||||
int arraySize;
|
||||
|
||||
// initial unsorted array
|
||||
int[] unsortedArray;
|
||||
|
||||
//cloned array to sort
|
||||
int[] arrayToSort;
|
||||
|
||||
@Setup(Level.Trial)
|
||||
public void createUnSortedArray() {
|
||||
unsortedArray = new int[arraySize];
|
||||
for (int i = 0; i < arraySize; i++) {
|
||||
unsortedArray[i] = new Random().nextInt(1000);
|
||||
}
|
||||
}
|
||||
|
||||
@Setup(Level.Invocation)
|
||||
public void createUnSortedArrayCopy() {
|
||||
arrayToSort = unsortedArray.clone();
|
||||
}
|
||||
|
||||
int[] getArrayToSort() {
|
||||
return arrayToSort;
|
||||
}
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void benchmark_arrays_parallel_sort(ArrayContainer d, Blackhole b) {
|
||||
int[] arr = d.getArrayToSort();
|
||||
Arrays.parallelSort(arr);
|
||||
b.consume(arr);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void benchmark_arrays_sort(ArrayContainer d, Blackhole b) {
|
||||
int[] arr = d.getArrayToSort();
|
||||
Arrays.sort(arr);
|
||||
b.consume(arr);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package com.baeldung.finallykeyword;
|
||||
|
||||
public class FinallyExample {
|
||||
|
||||
public void printCount(String count) {
|
||||
try {
|
||||
System.out.println("The count is " + Integer.parseInt(count));
|
||||
} catch (NumberFormatException e) {
|
||||
System.out.println("No count");
|
||||
} finally {
|
||||
System.out.println("In finally");
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,53 @@
|
|||
package com.baeldung.finallykeyword;
|
||||
|
||||
public class FinallyExecutedCases {
|
||||
|
||||
public void noExceptionFinally() {
|
||||
try {
|
||||
System.out.println("Inside try");
|
||||
} finally {
|
||||
System.out.println("Inside finally");
|
||||
}
|
||||
}
|
||||
|
||||
public void unhandledException() throws Exception {
|
||||
try {
|
||||
System.out.println("Inside try");
|
||||
throw new Exception();
|
||||
} finally {
|
||||
System.out.println("Inside finally");
|
||||
}
|
||||
}
|
||||
|
||||
public void handledException() {
|
||||
try {
|
||||
System.out.println("Inside try");
|
||||
throw new Exception();
|
||||
} catch (Exception e) {
|
||||
System.out.println("Inside catch");
|
||||
} finally {
|
||||
System.out.println("Inside finally");
|
||||
}
|
||||
}
|
||||
|
||||
public String returnFromTry() {
|
||||
try {
|
||||
System.out.println("Inside try");
|
||||
return "from try";
|
||||
} finally {
|
||||
System.out.println("Inside finally");
|
||||
}
|
||||
}
|
||||
|
||||
public String returnFromCatch() {
|
||||
try {
|
||||
System.out.println("Inside try");
|
||||
throw new Exception();
|
||||
} catch (Exception e) {
|
||||
System.out.println("Inside catch");
|
||||
return "from catch";
|
||||
} finally {
|
||||
System.out.println("Inside finally");
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,54 @@
|
|||
package com.baeldung.finallykeyword;
|
||||
|
||||
public class FinallyNotExecutedCases {
|
||||
|
||||
public void callingSystemExit() {
|
||||
try {
|
||||
System.out.println("Inside try");
|
||||
System.exit(1);
|
||||
} finally {
|
||||
System.out.println("Inside finally");
|
||||
}
|
||||
}
|
||||
|
||||
public void callingRuntimeHalt() {
|
||||
try {
|
||||
System.out.println("Inside try");
|
||||
Runtime.getRuntime()
|
||||
.halt(1);
|
||||
} finally {
|
||||
System.out.println("Inside finally");
|
||||
}
|
||||
}
|
||||
|
||||
public void infiniteLoop() {
|
||||
try {
|
||||
System.out.println("Inside try");
|
||||
while (true) {
|
||||
}
|
||||
} finally {
|
||||
System.out.println("Inside finally");
|
||||
}
|
||||
}
|
||||
|
||||
public void daemonThread() throws InterruptedException {
|
||||
Runnable runnable = () -> {
|
||||
try {
|
||||
System.out.println("Inside try");
|
||||
} finally {
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
System.out.println("Inside finally");
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
};
|
||||
Thread regular = new Thread(runnable);
|
||||
Thread daemon = new Thread(runnable);
|
||||
daemon.setDaemon(true);
|
||||
regular.start();
|
||||
Thread.sleep(300);
|
||||
daemon.start();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,33 @@
|
|||
package com.baeldung.finallykeyword;
|
||||
|
||||
public class PitfallsWhenUsingFinally {
|
||||
|
||||
public String disregardsUnCaughtException() {
|
||||
try {
|
||||
System.out.println("Inside try");
|
||||
throw new RuntimeException();
|
||||
} finally {
|
||||
System.out.println("Inside finally");
|
||||
return "from finally";
|
||||
}
|
||||
}
|
||||
|
||||
public String ignoringOtherReturns() {
|
||||
try {
|
||||
System.out.println("Inside try");
|
||||
return "from try";
|
||||
} finally {
|
||||
System.out.println("Inside finally");
|
||||
return "from finally";
|
||||
}
|
||||
}
|
||||
|
||||
public String throwsException() {
|
||||
try {
|
||||
System.out.println("Inside try");
|
||||
return "from try";
|
||||
} finally {
|
||||
throw new RuntimeException();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,49 @@
|
|||
package com.baeldung.methodmultiplereturnvalues;
|
||||
|
||||
public class Coordinates {
|
||||
|
||||
private double longitude;
|
||||
private double latitude;
|
||||
private String placeName;
|
||||
|
||||
public Coordinates() {}
|
||||
|
||||
public Coordinates(double longitude, double latitude, String placeName) {
|
||||
this.longitude = longitude;
|
||||
this.latitude = latitude;
|
||||
this.placeName = placeName;
|
||||
}
|
||||
|
||||
public double calculateDistance(Coordinates c) {
|
||||
|
||||
double s1 = Math.abs(this.longitude - c.longitude);
|
||||
double s2 = Math.abs(this.latitude - c.latitude);
|
||||
|
||||
return Math.hypot(s1, s2);
|
||||
}
|
||||
|
||||
public double getLongitude() {
|
||||
return longitude;
|
||||
}
|
||||
|
||||
public void setLongitude(double longitude) {
|
||||
this.longitude = longitude;
|
||||
}
|
||||
|
||||
public double getLatitude() {
|
||||
return latitude;
|
||||
}
|
||||
|
||||
public void setLatitude(double latitude) {
|
||||
this.latitude = latitude;
|
||||
}
|
||||
|
||||
public String getPlaceName() {
|
||||
return placeName;
|
||||
}
|
||||
|
||||
public void setPlaceName(String placeName) {
|
||||
this.placeName = placeName;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
package com.baeldung.methodmultiplereturnvalues;
|
||||
|
||||
class MultipleReturnValuesUsingArrays {
|
||||
|
||||
|
||||
static double[] getCoordinatesDoubleArray() {
|
||||
|
||||
double[] coordinates = new double[2];
|
||||
|
||||
coordinates[0] = 10;
|
||||
coordinates[1] = 12.5;
|
||||
|
||||
return coordinates;
|
||||
}
|
||||
|
||||
|
||||
static Number[] getCoordinatesNumberArray() {
|
||||
|
||||
Number[] coordinates = new Number[2];
|
||||
|
||||
coordinates[0] = 10; //Integer
|
||||
coordinates[1] = 12.5; //Double
|
||||
|
||||
return coordinates;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
package com.baeldung.methodmultiplereturnvalues;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
class MultipleReturnValuesUsingCollections {
|
||||
|
||||
static List<Number> getCoordinatesList() {
|
||||
|
||||
List<Number> coordinates = new ArrayList<>();
|
||||
|
||||
coordinates.add(10);
|
||||
coordinates.add(12.5);
|
||||
|
||||
return coordinates;
|
||||
}
|
||||
|
||||
static Map<String, Number> getCoordinatesMap() {
|
||||
|
||||
Map<String, Number> coordinates = new HashMap<>();
|
||||
|
||||
coordinates.put("longitude", 10);
|
||||
coordinates.put("latitude", 12.5);
|
||||
|
||||
return coordinates;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package com.baeldung.methodmultiplereturnvalues;
|
||||
|
||||
class MultipleReturnValuesUsingContainer {
|
||||
|
||||
static Coordinates getCoordinates() {
|
||||
|
||||
double longitude = 10;
|
||||
double latitude = 12.5;
|
||||
String placeName = "home";
|
||||
|
||||
return new Coordinates(longitude, latitude, placeName);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.methodmultiplereturnvalues;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
class MultipleReturnValuesUsingTuples {
|
||||
|
||||
static Tuple2<Coordinates, Double> getMostDistantPoint(List<Coordinates> coordinatesList,
|
||||
Coordinates target) {
|
||||
|
||||
return coordinatesList.stream()
|
||||
.map(coor -> new Tuple2<>(coor, coor.calculateDistance(target)))
|
||||
.max((d1, d2) -> Double.compare(d1.getSecond(), d2.getSecond()))
|
||||
.get();
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,31 @@
|
|||
package com.baeldung.methodmultiplereturnvalues;
|
||||
|
||||
public class Tuple2 <K, V> {
|
||||
|
||||
private K first;
|
||||
private V second;
|
||||
|
||||
public Tuple2() {}
|
||||
|
||||
public Tuple2(K first, V second) {
|
||||
this.first = first;
|
||||
this.second = second;
|
||||
}
|
||||
|
||||
public K getFirst() {
|
||||
return first;
|
||||
}
|
||||
|
||||
public V getSecond() {
|
||||
return second;
|
||||
}
|
||||
|
||||
public void setFirst(K first) {
|
||||
this.first = first;
|
||||
}
|
||||
|
||||
public void setSecond(V second) {
|
||||
this.second = second;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
package com.baeldung.finallykeyword;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class PitfallsWhenUsingFinallyUnitTest {
|
||||
|
||||
PitfallsWhenUsingFinally instance = new PitfallsWhenUsingFinally();
|
||||
|
||||
@Test
|
||||
public void testIgnoresException() {
|
||||
String result = instance.disregardsUnCaughtException();
|
||||
assertEquals("from finally", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIgnoresOtherReturns() {
|
||||
String result = instance.ignoringOtherReturns();
|
||||
assertEquals("from finally", result);
|
||||
}
|
||||
|
||||
@Test(expected = RuntimeException.class)
|
||||
public void testThrowsException() {
|
||||
instance.throwsException();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
package com.baeldung.methodmultiplereturnvalues;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class MultipleReturnValuesUsingArraysUnitTest {
|
||||
|
||||
@Test
|
||||
void whenUsingArrayOfDoubles_thenMultipleDoubleFieldsAreReturned() {
|
||||
|
||||
double[] coordinates = MultipleReturnValuesUsingArrays.getCoordinatesDoubleArray();
|
||||
assertEquals(10, coordinates[0]);
|
||||
assertEquals(12.5, coordinates[1]);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingArrayOfNumbers_thenMultipleNumberFieldsAreReturned() {
|
||||
|
||||
Number[] coordinates = MultipleReturnValuesUsingArrays.getCoordinatesNumberArray();
|
||||
assertEquals(10, coordinates[0]);
|
||||
assertEquals(12.5, coordinates[1]);
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
package com.baeldung.methodmultiplereturnvalues;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class MultipleReturnValuesUsingCollectionsUnitTest {
|
||||
|
||||
@Test
|
||||
void whenUsingList_thenMultipleFieldsAreReturned() {
|
||||
|
||||
List<Number> coordinates = MultipleReturnValuesUsingCollections.getCoordinatesList();
|
||||
assertEquals(Integer.valueOf(10), coordinates.get(0));
|
||||
assertEquals(Double.valueOf(12.5), coordinates.get(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingMap_thenMultipleFieldsAreReturned() {
|
||||
|
||||
Map<String, Number> coordinates = MultipleReturnValuesUsingCollections.getCoordinatesMap();
|
||||
assertEquals(Integer.valueOf(10), coordinates.get("longitude"));
|
||||
assertEquals(Double.valueOf(12.5), coordinates.get("latitude"));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.methodmultiplereturnvalues;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class MultipleReturnValuesUsingContainerUnitTest {
|
||||
|
||||
@Test
|
||||
void whenUsingContainerClass_thenMultipleFieldsAreReturned() {
|
||||
|
||||
Coordinates coordinates = MultipleReturnValuesUsingContainer.getCoordinates();
|
||||
|
||||
assertEquals(10, coordinates.getLongitude());
|
||||
assertEquals(12.5, coordinates.getLatitude());
|
||||
assertEquals("home", coordinates.getPlaceName());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,31 @@
|
|||
package com.baeldung.methodmultiplereturnvalues;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class MultipleReturnValuesUsingTuplesUnitTest {
|
||||
|
||||
@Test
|
||||
void whenUsingTuple_thenMultipleFieldsAreReturned() {
|
||||
|
||||
List<Coordinates> coordinatesList = new ArrayList<>();
|
||||
coordinatesList.add(new Coordinates(1, 1, "home"));
|
||||
coordinatesList.add(new Coordinates(2, 2, "school"));
|
||||
coordinatesList.add(new Coordinates(3, 3, "hotel"));
|
||||
|
||||
Coordinates target = new Coordinates(5, 5, "gym");
|
||||
|
||||
Tuple2<Coordinates, Double> mostDistantPoint = MultipleReturnValuesUsingTuples.getMostDistantPoint(coordinatesList, target);
|
||||
|
||||
assertEquals(1, mostDistantPoint.getFirst().getLongitude());
|
||||
assertEquals(1, mostDistantPoint.getFirst().getLatitude());
|
||||
assertEquals("home", mostDistantPoint.getFirst().getPlaceName());
|
||||
assertEquals(5.66, BigDecimal.valueOf(mostDistantPoint.getSecond()).setScale(2, RoundingMode.HALF_UP).doubleValue());
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,320 @@
|
|||
package com.baeldung.powerset;
|
||||
|
||||
import com.google.common.collect.Sets;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import java.util.AbstractSet;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.Set;
|
||||
|
||||
public class PowerSetUtility<T> {
|
||||
|
||||
private Map<T, Integer> map = new HashMap<>();
|
||||
private List<T> reverseMap = new ArrayList<>();
|
||||
|
||||
//Lazy Load PowerSet class
|
||||
private static class PowerSet<E> extends AbstractSet<Set<E>> {
|
||||
private Map<E, Integer> map = new HashMap<>();
|
||||
private List<E> reverseMap = new ArrayList<>();
|
||||
private Set<E> set;
|
||||
|
||||
public PowerSet(Set<E> set) {
|
||||
this.set = set;
|
||||
initializeMap();
|
||||
}
|
||||
|
||||
abstract class ListIterator<K> implements Iterator<K> {
|
||||
|
||||
protected int position = 0;
|
||||
private int size;
|
||||
|
||||
public ListIterator(int size) {
|
||||
this.size = size;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
return position < size;
|
||||
}
|
||||
}
|
||||
|
||||
static class Subset<E> extends AbstractSet<E> {
|
||||
private Map<E, Integer> map;
|
||||
private List<E> reverseMap;
|
||||
private int mask;
|
||||
|
||||
public Subset(Map<E, Integer> map, List<E> reverseMap, int mask) {
|
||||
this.map = map;
|
||||
this.reverseMap = reverseMap;
|
||||
this.mask = mask;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Iterator<E> iterator() {
|
||||
return new Iterator<E>() {
|
||||
int remainingSetBits = mask;
|
||||
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
return remainingSetBits != 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public E next() {
|
||||
int index = Integer.numberOfTrailingZeros(remainingSetBits);
|
||||
if (index == 32) {
|
||||
throw new NoSuchElementException();
|
||||
}
|
||||
remainingSetBits &= ~(1 << index);
|
||||
return reverseMap.get(index);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
return Integer.bitCount(mask);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean contains(@Nullable Object o) {
|
||||
Integer index = map.get(o);
|
||||
return index != null && (mask & (1 << index)) != 0;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Iterator<Set<E>> iterator() {
|
||||
return new ListIterator<Set<E>>(this.size()) {
|
||||
@Override
|
||||
public Set<E> next() {
|
||||
return new Subset<>(map, reverseMap, position++);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
return (1 << this.set.size());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean contains(@Nullable Object obj) {
|
||||
if (obj instanceof Set) {
|
||||
Set<?> set = (Set<?>) obj;
|
||||
return reverseMap.containsAll(set);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(@Nullable Object obj) {
|
||||
if (obj instanceof PowerSet) {
|
||||
PowerSet<?> that = (PowerSet<?>) obj;
|
||||
return set.equals(that.set);//Set equals check to have the same element regardless of the order of the items
|
||||
}
|
||||
return super.equals(obj);
|
||||
}
|
||||
|
||||
|
||||
private void initializeMap() {
|
||||
int mapId = 0;
|
||||
for (E c : this.set) {
|
||||
map.put(c, mapId++);
|
||||
reverseMap.add(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Set<Set<T>> lazyLoadPowerSet(Set<T> set) {
|
||||
return new PowerSet<>(set);
|
||||
}
|
||||
|
||||
public Set<Set<T>> recursivePowerSet(Set<T> set) {
|
||||
if (set.isEmpty()) {
|
||||
Set<Set<T>> ret = new HashSet<>();
|
||||
ret.add(set);
|
||||
return ret;
|
||||
}
|
||||
|
||||
T element = set.iterator().next();
|
||||
Set<T> subSetWithoutElement = getSubSetWithoutElement(set, element);
|
||||
Set<Set<T>> powerSetSubSetWithoutElement = recursivePowerSet(subSetWithoutElement);
|
||||
|
||||
Set<Set<T>> powerSetSubSetWithElement = addElementToAll(powerSetSubSetWithoutElement, element);
|
||||
|
||||
Set<Set<T>> powerSet = new HashSet<>();
|
||||
powerSet.addAll(powerSetSubSetWithoutElement);
|
||||
powerSet.addAll(powerSetSubSetWithElement);
|
||||
return powerSet;
|
||||
}
|
||||
|
||||
public Set<Set<T>> recursivePowerSetIndexRepresentation(Collection<T> set) {
|
||||
initializeMap(set);
|
||||
Set<Set<Integer>> powerSetIndices = recursivePowerSetIndexRepresentation(0, set.size());
|
||||
return unMapIndex(powerSetIndices);
|
||||
}
|
||||
|
||||
private List<List<Boolean>> iterativePowerSetByLoopOverNumbersWithReverseLexicographicalOrder(int n) {
|
||||
List<List<Boolean>> powerSet = new ArrayList<>();
|
||||
for (int i = 0; i < (1 << n); i++) {
|
||||
List<Boolean> subset = new ArrayList<>(n);
|
||||
for (int j = 0; j < n; j++)
|
||||
subset.add(((1 << j) & i) > 0);
|
||||
powerSet.add(subset);
|
||||
}
|
||||
return powerSet;
|
||||
}
|
||||
|
||||
private List<List<Boolean>> iterativePowerSetByLoopOverNumbersWithGrayCodeOrder(int n) {
|
||||
List<List<Boolean>> powerSet = new ArrayList<>();
|
||||
for (int i = 0; i < (1 << n); i++) {
|
||||
List<Boolean> subset = new ArrayList<>(n);
|
||||
for (int j = 0; j < n; j++) {
|
||||
int grayEquivalent = i ^ (i >> 1);
|
||||
subset.add(((1 << j) & grayEquivalent) > 0);
|
||||
}
|
||||
powerSet.add(subset);
|
||||
}
|
||||
return powerSet;
|
||||
}
|
||||
|
||||
public Set<Set<T>> recursivePowerSetBinaryRepresentation(Collection<T> set) {
|
||||
initializeMap(set);
|
||||
Set<List<Boolean>> powerSetBoolean = recursivePowerSetBinaryRepresentation(0, set.size());
|
||||
return unMapBinary(powerSetBoolean);
|
||||
}
|
||||
|
||||
public List<List<T>> iterativePowerSetByLoopOverNumbers(Set<T> set) {
|
||||
initializeMap(set);
|
||||
List<List<Boolean>> sets = iterativePowerSetByLoopOverNumbersWithReverseLexicographicalOrder(set.size());
|
||||
return unMapListBinary(sets);
|
||||
}
|
||||
|
||||
public List<List<T>> iterativePowerSetByLoopOverNumbersMinimalChange(Set<T> set) {
|
||||
initializeMap(set);
|
||||
List<List<Boolean>> sets = iterativePowerSetByLoopOverNumbersWithGrayCodeOrder(set.size());
|
||||
return unMapListBinary(sets);
|
||||
}
|
||||
|
||||
public static int getRankInLexicographicalOrder(List<Boolean> subset) {
|
||||
int rank = 0;
|
||||
for (int i = 0; i < subset.size(); i++)
|
||||
if (subset.get(i))
|
||||
rank += (1 << (subset.size() - i - 1));
|
||||
return rank;
|
||||
}
|
||||
|
||||
public static List<Boolean> getSubsetForRankInLexicographicalOrder(int rank, int sizeOfSet) {
|
||||
Boolean[] subset = new Boolean[sizeOfSet];
|
||||
for(int j = 0; j < sizeOfSet; j++) {
|
||||
subset[sizeOfSet - j - 1] = ((rank & (1 << j)) > 0);
|
||||
}
|
||||
return Arrays.asList(subset);
|
||||
}
|
||||
|
||||
private Set<Set<Integer>> recursivePowerSetIndexRepresentation(int idx, int n) {
|
||||
if (idx == n) {
|
||||
Set<Set<Integer>> empty = new HashSet<>();
|
||||
empty.add(new HashSet<>());
|
||||
return empty;
|
||||
}
|
||||
Set<Set<Integer>> powerSetSubset = recursivePowerSetIndexRepresentation(idx + 1, n);
|
||||
Set<Set<Integer>> powerSet = new HashSet<>(powerSetSubset);
|
||||
for (Set<Integer> s : powerSetSubset) {
|
||||
HashSet<Integer> subSetIdxInclusive = new HashSet<>(s);
|
||||
subSetIdxInclusive.add(idx);
|
||||
powerSet.add(subSetIdxInclusive);
|
||||
}
|
||||
return powerSet;
|
||||
}
|
||||
|
||||
private Set<List<Boolean>> recursivePowerSetBinaryRepresentation(int idx, int n) {
|
||||
if (idx == n) {
|
||||
Set<List<Boolean>> powerSetOfEmptySet = new HashSet<>();
|
||||
powerSetOfEmptySet.add(Arrays.asList(new Boolean[n]));
|
||||
return powerSetOfEmptySet;
|
||||
}
|
||||
Set<List<Boolean>> powerSetSubset = recursivePowerSetBinaryRepresentation(idx + 1, n);
|
||||
Set<List<Boolean>> powerSet = new HashSet<>();
|
||||
for (List<Boolean> s : powerSetSubset) {
|
||||
List<Boolean> subSetIdxExclusive = new ArrayList<>(s);
|
||||
subSetIdxExclusive.set(idx, false);
|
||||
powerSet.add(subSetIdxExclusive);
|
||||
List<Boolean> subSetIdxInclusive = new ArrayList<>(s);
|
||||
subSetIdxInclusive.set(idx, true);
|
||||
powerSet.add(subSetIdxInclusive);
|
||||
}
|
||||
return powerSet;
|
||||
}
|
||||
|
||||
private void initializeMap(Collection<T> collection) {
|
||||
int mapId = 0;
|
||||
for (T c : collection) {
|
||||
map.put(c, mapId++);
|
||||
reverseMap.add(c);
|
||||
}
|
||||
}
|
||||
|
||||
private Set<Set<T>> unMapIndex(Set<Set<Integer>> sets) {
|
||||
Set<Set<T>> ret = new HashSet<>();
|
||||
for (Set<Integer> s : sets) {
|
||||
HashSet<T> subset = new HashSet<>();
|
||||
for (Integer i : s)
|
||||
subset.add(reverseMap.get(i));
|
||||
ret.add(subset);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
private Set<Set<T>> unMapBinary(Collection<List<Boolean>> sets) {
|
||||
Set<Set<T>> ret = new HashSet<>();
|
||||
for (List<Boolean> s : sets) {
|
||||
HashSet<T> subset = new HashSet<>();
|
||||
for (int i = 0; i < s.size(); i++)
|
||||
if (s.get(i))
|
||||
subset.add(reverseMap.get(i));
|
||||
ret.add(subset);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
private List<List<T>> unMapListBinary(Collection<List<Boolean>> sets) {
|
||||
List<List<T>> ret = new ArrayList<>();
|
||||
for (List<Boolean> s : sets) {
|
||||
List<T> subset = new ArrayList<>();
|
||||
for (int i = 0; i < s.size(); i++)
|
||||
if (s.get(i))
|
||||
subset.add(reverseMap.get(i));
|
||||
ret.add(subset);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
private Set<Set<T>> addElementToAll(Set<Set<T>> powerSetSubSetWithoutElement, T element) {
|
||||
Set<Set<T>> powerSetSubSetWithElement = new HashSet<>();
|
||||
for (Set<T> subsetWithoutElement : powerSetSubSetWithoutElement) {
|
||||
Set<T> subsetWithElement = new HashSet<>(subsetWithoutElement);
|
||||
subsetWithElement.add(element);
|
||||
powerSetSubSetWithElement.add(subsetWithElement);
|
||||
}
|
||||
return powerSetSubSetWithElement;
|
||||
}
|
||||
|
||||
private Set<T> getSubSetWithoutElement(Set<T> set, T element) {
|
||||
Set<T> subsetWithoutElement = new HashSet<>();
|
||||
for (T s : set) {
|
||||
if (!s.equals(element))
|
||||
subsetWithoutElement.add(s);
|
||||
}
|
||||
return subsetWithoutElement;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,225 @@
|
|||
package com.baeldung.powerset;
|
||||
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.common.collect.Sets;
|
||||
import org.hamcrest.MatcherAssert;
|
||||
import org.hamcrest.Matchers;
|
||||
import org.hamcrest.collection.IsCollectionWithSize;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Random;
|
||||
import java.util.Set;
|
||||
|
||||
public class PowerSetUtilityUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenSet_WhenGuavaLibraryGeneratePowerSet_ThenItContainsAllSubsets() {
|
||||
ImmutableSet<String> set = ImmutableSet.of("APPLE", "ORANGE", "MANGO");
|
||||
Set<Set<String>> powerSet = Sets.powerSet(set);
|
||||
Assertions.assertEquals((1 << set.size()), powerSet.size());
|
||||
MatcherAssert.assertThat(powerSet, Matchers.containsInAnyOrder(
|
||||
ImmutableSet.of(),
|
||||
ImmutableSet.of("APPLE"),
|
||||
ImmutableSet.of("ORANGE"),
|
||||
ImmutableSet.of("APPLE", "ORANGE"),
|
||||
ImmutableSet.of("MANGO"),
|
||||
ImmutableSet.of("APPLE", "MANGO"),
|
||||
ImmutableSet.of("ORANGE", "MANGO"),
|
||||
ImmutableSet.of("APPLE", "ORANGE", "MANGO")
|
||||
));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSet_WhenPowerSetIsLazyLoadGenerated_ThenItContainsAllSubsets() {
|
||||
Set<String> set = RandomSetOfStringGenerator.generateRandomSet();
|
||||
Set<Set<String>> powerSet = new PowerSetUtility<String>().lazyLoadPowerSet(set);
|
||||
|
||||
//To make sure that the size of power set is (2 power n)
|
||||
MatcherAssert.assertThat(powerSet, IsCollectionWithSize.hasSize((1 << set.size())));
|
||||
//To make sure that number of occurrence of each element is (2 power n-1)
|
||||
Map<String, Integer> counter = new HashMap<>();
|
||||
for (Set<String> subset : powerSet) {
|
||||
for (String name : subset) {
|
||||
int num = counter.getOrDefault(name, 0);
|
||||
counter.put(name, num + 1);
|
||||
}
|
||||
}
|
||||
counter.forEach((k, v) -> Assertions.assertEquals((1 << (set.size() - 1)), v.intValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSet_WhenPowerSetIsCalculated_ThenItContainsAllSubsets() {
|
||||
Set<String> set = RandomSetOfStringGenerator.generateRandomSet();
|
||||
|
||||
Set<Set<String>> powerSet = new PowerSetUtility<String>().recursivePowerSet(set);
|
||||
|
||||
//To make sure that the size of power set is (2 power n)
|
||||
MatcherAssert.assertThat(powerSet, IsCollectionWithSize.hasSize((1 << set.size())));
|
||||
//To make sure that number of occurrence of each element is (2 power n-1)
|
||||
Map<String, Integer> counter = new HashMap<>();
|
||||
for (Set<String> subset : powerSet) {
|
||||
for (String name : subset) {
|
||||
int num = counter.getOrDefault(name, 0);
|
||||
counter.put(name, num + 1);
|
||||
}
|
||||
}
|
||||
counter.forEach((k, v) -> Assertions.assertEquals((1 << (set.size() - 1)), v.intValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSet_WhenPowerSetIsCalculatedRecursiveByIndexRepresentation_ThenItContainsAllSubsets() {
|
||||
Set<String> set = RandomSetOfStringGenerator.generateRandomSet();
|
||||
|
||||
Set<Set<String>> powerSet = new PowerSetUtility<String>().recursivePowerSetIndexRepresentation(set);
|
||||
|
||||
//To make sure that the size of power set is (2 power n)
|
||||
MatcherAssert.assertThat(powerSet, IsCollectionWithSize.hasSize((1 << set.size())));
|
||||
//To make sure that number of occurrence of each element is (2 power n-1)
|
||||
Map<String, Integer> counter = new HashMap<>();
|
||||
for (Set<String> subset : powerSet) {
|
||||
for (String name : subset) {
|
||||
int num = counter.getOrDefault(name, 0);
|
||||
counter.put(name, num + 1);
|
||||
}
|
||||
}
|
||||
counter.forEach((k, v) -> Assertions.assertEquals((1 << (set.size() - 1)), v.intValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSet_WhenPowerSetIsCalculatedRecursiveByBinaryRepresentation_ThenItContainsAllSubsets() {
|
||||
Set<String> set = RandomSetOfStringGenerator.generateRandomSet();
|
||||
|
||||
Set<Set<String>> powerSet = new PowerSetUtility<String>().recursivePowerSetBinaryRepresentation(set);
|
||||
|
||||
//To make sure that the size of power set is (2 power n)
|
||||
MatcherAssert.assertThat(powerSet, IsCollectionWithSize.hasSize((1 << set.size())));
|
||||
//To make sure that number of occurrence of each element is (2 power n-1)
|
||||
Map<String, Integer> counter = new HashMap<>();
|
||||
for (Set<String> subset : powerSet) {
|
||||
for (String name : subset) {
|
||||
int num = counter.getOrDefault(name, 0);
|
||||
counter.put(name, num + 1);
|
||||
}
|
||||
}
|
||||
counter.forEach((k, v) -> Assertions.assertEquals((1 << (set.size() - 1)), v.intValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSet_WhenPowerSetIsCalculatedIterativePowerSetByLoopOverNumbers_ThenItContainsAllSubsets() {
|
||||
Set<String> set = RandomSetOfStringGenerator.generateRandomSet();
|
||||
|
||||
List<List<String>> powerSet = new PowerSetUtility<String>().iterativePowerSetByLoopOverNumbers(set);
|
||||
|
||||
//To make sure that the size of power set is (2 power n)
|
||||
MatcherAssert.assertThat(powerSet, IsCollectionWithSize.hasSize((1 << set.size())));
|
||||
//To make sure that number of occurrence of each element is (2 power n-1)
|
||||
Map<String, Integer> counter = new HashMap<>();
|
||||
for (List<String> subset : powerSet) {
|
||||
for (String name : subset) {
|
||||
int num = counter.getOrDefault(name, 0);
|
||||
counter.put(name, num + 1);
|
||||
}
|
||||
}
|
||||
counter.forEach((k, v) -> Assertions.assertEquals((1 << (set.size() - 1)), v.intValue()));
|
||||
//To make sure that one subset is not generated twice
|
||||
Assertions.assertEquals(powerSet.size(), new HashSet<>(powerSet).size());
|
||||
//To make sure that each element in each subset is occurred once
|
||||
for (List<String> subset : powerSet) {
|
||||
Assertions.assertEquals(subset.size(), new HashSet<>(subset).size());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSet_WhenPowerSetIsCalculatedIterativePowerSetByLoopOverNumbersMinimalChange_ThenItContainsAllSubsetsInGrayOrder() {
|
||||
|
||||
Set<String> set = RandomSetOfStringGenerator.generateRandomSet();
|
||||
List<List<String>> powerSet = new PowerSetUtility<String>().iterativePowerSetByLoopOverNumbersMinimalChange(set);
|
||||
|
||||
//To make sure that the size of power set is (2 power n)
|
||||
MatcherAssert.assertThat(powerSet, IsCollectionWithSize.hasSize((1 << set.size())));
|
||||
//To make sure that number of occurrence of each element is (2 power n-1)
|
||||
Map<String, Integer> counter = new HashMap<>();
|
||||
for (List<String> subset : powerSet) {
|
||||
for (String name : subset) {
|
||||
int num = counter.getOrDefault(name, 0);
|
||||
counter.put(name, num + 1);
|
||||
}
|
||||
}
|
||||
counter.forEach((k, v) -> Assertions.assertEquals((1 << (set.size() - 1)), v.intValue()));
|
||||
//To make sure that one subset is not generated twice
|
||||
Assertions.assertEquals(powerSet.size(), new HashSet<>(powerSet).size());
|
||||
//To make sure that each element in each subset is occurred once
|
||||
for (List<String> subset : powerSet) {
|
||||
Assertions.assertEquals(subset.size(), new HashSet<>(subset).size());
|
||||
}
|
||||
//To make sure that difference of consecutive subsets is exactly 1
|
||||
for(int i=1; i<powerSet.size(); i++) {
|
||||
int diff = 0;
|
||||
for (String s : powerSet.get(i - 1))
|
||||
if (!powerSet.get(i).contains(s))
|
||||
diff++;
|
||||
for (String s : powerSet.get(i))
|
||||
if (!powerSet.get(i - 1).contains(s))
|
||||
diff++;
|
||||
Assertions.assertEquals(1, diff);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSubset_WhenPowerSetIsInLexicographicalOrder_ReturnCorrectRank() {
|
||||
int n = new Random().nextInt(5) + 5; //a number in [5, 10)
|
||||
for(int i = 0; i < ( 1 << n); i++) {
|
||||
Boolean[] subset = new Boolean[n];
|
||||
for(int j=0; j < n; j++) {
|
||||
subset[n - j - 1] = ((i & (1 << j)) > 0);
|
||||
}
|
||||
Assertions.assertEquals(i, PowerSetUtility.getRankInLexicographicalOrder(Arrays.asList(subset)));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRanking_WhenPowerSetIsInLexicographicalOrder_ReturnTheSubset() {
|
||||
int n = new Random().nextInt(5) + 5; //a number in [5, 10)
|
||||
List<List<Boolean>> powerSet = new ArrayList<>();
|
||||
for(int i = 0; i < (1 << n); i++) {
|
||||
powerSet.add(PowerSetUtility.getSubsetForRankInLexicographicalOrder(i, n));
|
||||
}
|
||||
//To make sure that the size of power set is (2 power n)
|
||||
MatcherAssert.assertThat(powerSet, IsCollectionWithSize.hasSize((1 << n)));
|
||||
//To make sure that number of occurrence of each index is (2 power n-1)
|
||||
Map<Integer, Integer> counter = new HashMap<>();
|
||||
for (List<Boolean> subset : powerSet) {
|
||||
for (int i = 0; i < subset.size(); i++) {
|
||||
if(subset.get(i)) {
|
||||
int num = counter.getOrDefault(i, 0);
|
||||
counter.put(i, num + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
counter.forEach((k, v) -> Assertions.assertEquals((1 << (n - 1)), v.intValue()));
|
||||
//To make sure that one subset is not generated twice
|
||||
Assertions.assertEquals(powerSet.size(), new HashSet<>(powerSet).size());
|
||||
}
|
||||
|
||||
static class RandomSetOfStringGenerator {
|
||||
private static List<String> fruits = Arrays.asList("Apples", "Avocados", "Banana", "Blueberry", "Cherry", "Clementine", "Cucumber", "Date", "Fig",
|
||||
"Grapefruit"/*, "Grape", "Kiwi", "Lemon", "Mango", "Mulberry", "Melon", "Nectarine", "Olive", "Orange"*/);
|
||||
|
||||
static Set<String> generateRandomSet() {
|
||||
Set<String> set = new HashSet<>();
|
||||
Random random = new Random();
|
||||
int size = random.nextInt(fruits.size());
|
||||
while (set.size() != size) {
|
||||
set.add(fruits.get(random.nextInt(fruits.size())));
|
||||
}
|
||||
return set;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -128,7 +128,7 @@
|
|||
<geronimo-json_1.1_spec.version>1.0</geronimo-json_1.1_spec.version>
|
||||
<commons-collections4.version>4.1</commons-collections4.version>
|
||||
<project-reactor-test>3.1.6.RELEASE</project-reactor-test>
|
||||
<spring-boot.version>2.2.1.RELEASE</spring-boot.version>
|
||||
<spring-boot.version>2.2.2.RELEASE</spring-boot.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -1,11 +1,7 @@
|
|||
package com.baeldung.reactive.functional;
|
||||
|
||||
import static org.mockito.BDDMockito.given;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import com.baeldung.webflux.Employee;
|
||||
import com.baeldung.webflux.EmployeeRepository;
|
||||
import org.junit.FixMethodOrder;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
@ -15,13 +11,15 @@ import org.springframework.boot.test.context.SpringBootTest;
|
|||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.web.reactive.server.WebTestClient;
|
||||
|
||||
import com.baeldung.webflux.Employee;
|
||||
import com.baeldung.webflux.EmployeeRepository;
|
||||
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.mockito.BDDMockito.given;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = EmployeeSpringFunctionalApplication.class)
|
||||
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
|
||||
|
@ -58,15 +56,11 @@ public class EmployeeSpringFunctionalIntegrationTest {
|
|||
.bindToRouterFunction(config.getAllEmployeesRoute())
|
||||
.build();
|
||||
|
||||
List<Employee> employeeList = new ArrayList<>();
|
||||
List<Employee> employees = Arrays.asList(
|
||||
new Employee("1", "Employee 1"),
|
||||
new Employee("2", "Employee 2"));
|
||||
|
||||
Employee employee1 = new Employee("1", "Employee 1");
|
||||
Employee employee2 = new Employee("2", "Employee 2");
|
||||
|
||||
employeeList.add(employee1);
|
||||
employeeList.add(employee2);
|
||||
|
||||
Flux<Employee> employeeFlux = Flux.fromIterable(employeeList);
|
||||
Flux<Employee> employeeFlux = Flux.fromIterable(employees);
|
||||
given(employeeRepository.findAllEmployees()).willReturn(employeeFlux);
|
||||
|
||||
client.get()
|
||||
|
@ -75,7 +69,7 @@ public class EmployeeSpringFunctionalIntegrationTest {
|
|||
.expectStatus()
|
||||
.isOk()
|
||||
.expectBodyList(Employee.class)
|
||||
.isEqualTo(employeeList);
|
||||
.isEqualTo(employees);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
|
|
@ -6,7 +6,6 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
|
|||
@SpringBootApplication
|
||||
public class Application {
|
||||
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(Application.class, args);
|
||||
}
|
||||
|
|
|
@ -1,54 +1,54 @@
|
|||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
|
||||
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
|
||||
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
|
||||
xmlns:task="http://www.springframework.org/schema/task"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">
|
||||
|
||||
<bean id="sampleAdder"
|
||||
class="com.baeldung.logger.SampleAdder" />
|
||||
|
||||
<bean id="doBeforeAspect" class="com.baeldung.logger.AdderBeforeAspect" />
|
||||
<bean id="doAfterAspect" class="com.baeldung.logger.AdderAfterAspect" />
|
||||
<bean id="doAfterThrowingAspect" class="com.baeldung.logger.AdderAfterThrowAspect" />
|
||||
<bean id="doAfterReturningAspect" class="com.baeldung.logger.AdderAfterReturnAspect" />
|
||||
<bean id="doAroundAspect" class="com.baeldung.logger.AdderAroundAspect" />
|
||||
|
||||
<aop:config>
|
||||
|
||||
<aop:aspect id="aspects" ref="doBeforeAspect">
|
||||
<aop:pointcut id="pointCutBefore"
|
||||
expression="execution(* com.baeldung.logger.SampleAdder+.*(..))" />
|
||||
<aop:before method="beforeAdvice" pointcut-ref="pointCutBefore" />
|
||||
</aop:aspect>
|
||||
|
||||
<aop:aspect id="aspects" ref="doAfterAspect">
|
||||
<aop:pointcut id="pointCutAfter"
|
||||
expression="execution(* com.baeldung.logger.SampleAdder+.*(..))" />
|
||||
<aop:after method="afterAdvice" pointcut-ref="pointCutAfter" />
|
||||
</aop:aspect>
|
||||
|
||||
<aop:aspect id="aspects" ref="doAfterReturningAspect">
|
||||
<aop:pointcut id="pointCutAfterReturning"
|
||||
expression="execution(* com.baeldung.logger.SampleAdder+.*(..))" />
|
||||
<aop:after-returning method="afterReturn"
|
||||
returning="returnValue" pointcut-ref="pointCutAfterReturning" />
|
||||
</aop:aspect>
|
||||
|
||||
<aop:aspect id="aspects" ref="doAfterThrowingAspect">
|
||||
<aop:pointcut id="pointCutAfterThrowing"
|
||||
expression="execution(* com.baeldung.logger.SampleAdder+.*(..))" />
|
||||
<aop:after-throwing method="afterThrow"
|
||||
throwing="error" pointcut-ref="pointCutAfterThrowing" />
|
||||
</aop:aspect>
|
||||
|
||||
<aop:aspect id="aspects" ref="doAroundAspect">
|
||||
<aop:pointcut id="pointCutAround"
|
||||
expression="execution(* com.baeldung.logger.SampleAdder+.*(..))" />
|
||||
<aop:around method="aroundAdvice" pointcut-ref="pointCutAround" />
|
||||
</aop:aspect>
|
||||
|
||||
|
||||
</aop:config>
|
||||
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
|
||||
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
|
||||
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
|
||||
xmlns:task="http://www.springframework.org/schema/task"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">
|
||||
|
||||
<bean id="sampleAdder"
|
||||
class="com.baeldung.logger.SampleAdder" />
|
||||
|
||||
<bean id="doBeforeAspect" class="com.baeldung.logger.AdderBeforeAspect" />
|
||||
<bean id="doAfterAspect" class="com.baeldung.logger.AdderAfterAspect" />
|
||||
<bean id="doAfterThrowingAspect" class="com.baeldung.logger.AdderAfterThrowAspect" />
|
||||
<bean id="doAfterReturningAspect" class="com.baeldung.logger.AdderAfterReturnAspect" />
|
||||
<bean id="doAroundAspect" class="com.baeldung.logger.AdderAroundAspect" />
|
||||
|
||||
<aop:config>
|
||||
|
||||
<aop:aspect id="aspects" ref="doBeforeAspect">
|
||||
<aop:pointcut id="pointCutBefore"
|
||||
expression="execution(* com.baeldung.logger.SampleAdder+.*(..))" />
|
||||
<aop:before method="beforeAdvice" pointcut-ref="pointCutBefore" />
|
||||
</aop:aspect>
|
||||
|
||||
<aop:aspect id="aspects" ref="doAfterAspect">
|
||||
<aop:pointcut id="pointCutAfter"
|
||||
expression="execution(* com.baeldung.logger.SampleAdder+.*(..))" />
|
||||
<aop:after method="afterAdvice" pointcut-ref="pointCutAfter" />
|
||||
</aop:aspect>
|
||||
|
||||
<aop:aspect id="aspects" ref="doAfterReturningAspect">
|
||||
<aop:pointcut id="pointCutAfterReturning"
|
||||
expression="execution(* com.baeldung.logger.SampleAdder+.*(..))" />
|
||||
<aop:after-returning method="afterReturn"
|
||||
returning="returnValue" pointcut-ref="pointCutAfterReturning" />
|
||||
</aop:aspect>
|
||||
|
||||
<aop:aspect id="aspects" ref="doAfterThrowingAspect">
|
||||
<aop:pointcut id="pointCutAfterThrowing"
|
||||
expression="execution(* com.baeldung.logger.SampleAdder+.*(..))" />
|
||||
<aop:after-throwing method="afterThrow"
|
||||
throwing="error" pointcut-ref="pointCutAfterThrowing" />
|
||||
</aop:aspect>
|
||||
|
||||
<aop:aspect id="aspects" ref="doAroundAspect">
|
||||
<aop:pointcut id="pointCutAround"
|
||||
expression="execution(* com.baeldung.logger.SampleAdder+.*(..))" />
|
||||
<aop:around method="aroundAdvice" pointcut-ref="pointCutAround" />
|
||||
</aop:aspect>
|
||||
|
||||
|
||||
</aop:config>
|
||||
|
||||
</beans>
|
|
@ -1,11 +0,0 @@
|
|||
package com.baeldung;
|
||||
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.EnableAspectJAutoProxy;
|
||||
|
||||
@Configuration
|
||||
@ComponentScan(basePackages = { "com.baeldung.pointcutadvice" })
|
||||
@EnableAspectJAutoProxy
|
||||
public class TestConfig {
|
||||
}
|
|
@ -1,6 +1,6 @@
|
|||
package com.baeldung.pointcutadvice;
|
||||
|
||||
import com.baeldung.TestConfig;
|
||||
import com.baeldung.Application;
|
||||
import com.baeldung.pointcutadvice.dao.FooDao;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
@ -23,7 +23,7 @@ import static org.junit.Assert.assertThat;
|
|||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = {TestConfig.class}, loader = AnnotationConfigContextLoader.class)
|
||||
@ContextConfiguration(classes = {Application.class}, loader = AnnotationConfigContextLoader.class)
|
||||
public class AopLoggingIntegrationTest {
|
||||
|
||||
@Before
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
package com.baeldung.pointcutadvice;
|
||||
|
||||
import com.baeldung.TestConfig;
|
||||
import com.baeldung.Application;
|
||||
import com.baeldung.pointcutadvice.dao.FooDao;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
@ -23,7 +23,7 @@ import static org.junit.Assert.assertThat;
|
|||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class)
|
||||
@ContextConfiguration(classes = {Application.class}, loader = AnnotationConfigContextLoader.class)
|
||||
public class AopPerformanceIntegrationTest {
|
||||
|
||||
@Before
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
package com.baeldung.pointcutadvice;
|
||||
|
||||
import com.baeldung.TestConfig;
|
||||
import com.baeldung.Application;
|
||||
import com.baeldung.pointcutadvice.dao.FooDao;
|
||||
import com.baeldung.pointcutadvice.events.FooCreationEventListener;
|
||||
import org.junit.Before;
|
||||
|
@ -21,7 +21,7 @@ import java.util.regex.Pattern;
|
|||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = {TestConfig.class}, loader = AnnotationConfigContextLoader.class)
|
||||
@ContextConfiguration(classes = {Application.class}, loader = AnnotationConfigContextLoader.class)
|
||||
public class AopPublishingIntegrationTest {
|
||||
|
||||
@Before
|
||||
|
|
Loading…
Reference in New Issue