commit
8e5a2ba1fe
|
@ -1,4 +1,6 @@
|
|||
## Relevant articles:
|
||||
|
||||
- [Introduction to Jenetics Library](http://www.baeldung.com/jenetics)
|
||||
- [Ant Colony Optimization](http://www.baeldung.com/java-ant-colony-optimization)
|
||||
- [Ant Colony Optimization](http://www.baeldung.com/java-ant-colony-optimization)
|
||||
- [Design a Genetic Algorithm in Java](https://www.baeldung.com/java-genetic-algorithm)
|
||||
- [The Traveling Salesman Problem in Java](https://www.baeldung.com/java-simulated-annealing-for-traveling-salesman)
|
||||
|
|
|
@ -1 +0,0 @@
|
|||
/bin/
|
|
@ -1,20 +0,0 @@
|
|||
package com.java.src;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
public class RoundUpToHundred {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
double input = scanner.nextDouble();
|
||||
scanner.close();
|
||||
|
||||
RoundUpToHundred.round(input);
|
||||
}
|
||||
|
||||
static long round(double input) {
|
||||
long i = (long) Math.ceil(input);
|
||||
return ((i + 99) / 100) * 100;
|
||||
};
|
||||
|
||||
}
|
|
@ -1,14 +0,0 @@
|
|||
package com.java.src;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class RoundUpToHundredTest {
|
||||
@Test
|
||||
public void givenInput_whenRound_thenRoundUpToTheNearestHundred() {
|
||||
assertEquals("Rounded up to hundred", 100, RoundUpToHundred.round(99));
|
||||
assertEquals("Rounded up to three hundred ", 300, RoundUpToHundred.round(200.2));
|
||||
assertEquals("Returns same rounded value", 400, RoundUpToHundred.round(400));
|
||||
}
|
||||
}
|
|
@ -5,7 +5,6 @@ import java.util.Scanner;
|
|||
import com.baeldung.algorithms.ga.annealing.SimulatedAnnealing;
|
||||
import com.baeldung.algorithms.ga.ant_colony.AntColonyOptimization;
|
||||
import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm;
|
||||
import com.baeldung.algorithms.slope_one.SlopeOne;
|
||||
|
||||
public class RunAlgorithm {
|
||||
|
||||
|
@ -13,11 +12,8 @@ public class RunAlgorithm {
|
|||
Scanner in = new Scanner(System.in);
|
||||
System.out.println("Run algorithm:");
|
||||
System.out.println("1 - Simulated Annealing");
|
||||
System.out.println("2 - Slope One");
|
||||
System.out.println("3 - Simple Genetic Algorithm");
|
||||
System.out.println("4 - Ant Colony");
|
||||
System.out.println("5 - Dijkstra");
|
||||
System.out.println("6 - All pairs in an array that add up to a given sum");
|
||||
System.out.println("2 - Simple Genetic Algorithm");
|
||||
System.out.println("3 - Ant Colony");
|
||||
int decision = in.nextInt();
|
||||
switch (decision) {
|
||||
case 1:
|
||||
|
@ -25,19 +21,13 @@ public class RunAlgorithm {
|
|||
"Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995));
|
||||
break;
|
||||
case 2:
|
||||
SlopeOne.slopeOne(3);
|
||||
break;
|
||||
case 3:
|
||||
SimpleGeneticAlgorithm ga = new SimpleGeneticAlgorithm();
|
||||
ga.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111");
|
||||
break;
|
||||
case 4:
|
||||
case 3:
|
||||
AntColonyOptimization antColony = new AntColonyOptimization(21);
|
||||
antColony.startAntOptimization();
|
||||
break;
|
||||
case 5:
|
||||
System.out.println("Please run the DijkstraAlgorithmTest.");
|
||||
break;
|
||||
default:
|
||||
System.out.println("Unknown option");
|
||||
break;
|
||||
|
|
|
@ -9,4 +9,5 @@
|
|||
- [How to Find the Kth Largest Element in Java](http://www.baeldung.com/java-kth-largest-element)
|
||||
- [Multi-Swarm Optimization Algorithm in Java](http://www.baeldung.com/java-multi-swarm-algorithm)
|
||||
- [String Search Algorithms for Large Texts](http://www.baeldung.com/java-full-text-search-algorithms)
|
||||
- [Check If a String Contains All The Letters of The Alphabet](https://www.baeldung.com/java-string-contains-all-letters)
|
||||
- [Check If a String Contains All The Letters of The Alphabet](https://www.baeldung.com/java-string-contains-all-letters)
|
||||
- [Find the Middle Element of a Linked List](http://www.baeldung.com/java-linked-list-middle-element)
|
|
@ -1 +0,0 @@
|
|||
/bin/
|
|
@ -1,14 +0,0 @@
|
|||
package com.java.src;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class RoundUpToHundredTest {
|
||||
@Test
|
||||
public void givenInput_whenRound_thenRoundUpToTheNearestHundred() {
|
||||
assertEquals("Rounded up to hundred", 100, RoundUpToHundred.round(99));
|
||||
assertEquals("Rounded up to three hundred ", 300, RoundUpToHundred.round(200.2));
|
||||
assertEquals("Returns same rounded value", 400, RoundUpToHundred.round(400));
|
||||
}
|
||||
}
|
|
@ -1,12 +0,0 @@
|
|||
S ########
|
||||
# #
|
||||
# ### ## #
|
||||
# # # #
|
||||
# # # # #
|
||||
# ## #####
|
||||
# # #
|
||||
# # # # #
|
||||
##### ####
|
||||
# # E
|
||||
# # # #
|
||||
##########
|
|
@ -1,22 +0,0 @@
|
|||
S ##########################
|
||||
# # # #
|
||||
# # #### ############### #
|
||||
# # # # # #
|
||||
# # #### # # ###############
|
||||
# # # # # # #
|
||||
# # # #### ### ########### #
|
||||
# # # # # #
|
||||
# ################## #
|
||||
######### # # # # #
|
||||
# # #### # ####### # #
|
||||
# # ### ### # # # # #
|
||||
# # ## # ##### # #
|
||||
##### ####### # # # # #
|
||||
# # ## ## #### # #
|
||||
# ##### ####### # #
|
||||
# # ############
|
||||
####### ######### # #
|
||||
# # ######## #
|
||||
# ####### ###### ## # E
|
||||
# # # ## #
|
||||
############################
|
|
@ -10,7 +10,6 @@
|
|||
- [A Collaborative Filtering Recommendation System in Java](http://www.baeldung.com/java-collaborative-filtering-recommendations)
|
||||
- [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)
|
||||
- [Find the Middle Element of a Linked List](http://www.baeldung.com/java-linked-list-middle-element)
|
||||
- [An Introduction to the Theory of Big-O Notation](http://www.baeldung.com/big-o-notation)
|
||||
- [Check If Two Rectangles Overlap In Java](https://www.baeldung.com/java-check-if-two-rectangles-overlap)
|
||||
- [Calculate the Distance Between Two Points in Java](https://www.baeldung.com/java-distance-between-two-points)
|
||||
|
|
|
@ -1 +0,0 @@
|
|||
/bin/
|
|
@ -1,20 +0,0 @@
|
|||
package com.java.src;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
public class RoundUpToHundred {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
double input = scanner.nextDouble();
|
||||
scanner.close();
|
||||
|
||||
RoundUpToHundred.round(input);
|
||||
}
|
||||
|
||||
static long round(double input) {
|
||||
long i = (long) Math.ceil(input);
|
||||
return ((i + 99) / 100) * 100;
|
||||
};
|
||||
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
package com.baeldung.algorithms;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
import com.baeldung.algorithms.slope_one.SlopeOne;
|
||||
|
||||
public class RunAlgorithm {
|
||||
|
||||
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
|
||||
Scanner in = new Scanner(System.in);
|
||||
System.out.println("1 - Slope One");
|
||||
System.out.println("2 - Dijkstra");
|
||||
int decision = in.nextInt();
|
||||
switch (decision) {
|
||||
case 1:
|
||||
SlopeOne.slopeOne(3);
|
||||
break;
|
||||
case 2:
|
||||
System.out.println("Please run the DijkstraAlgorithmLongRunningUnitTest.");
|
||||
break;
|
||||
default:
|
||||
System.out.println("Unknown option");
|
||||
break;
|
||||
}
|
||||
in.close();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
package com.baeldung.algorithms.mercator;
|
||||
|
||||
class EllipticalMercator extends Mercator {
|
||||
|
||||
@Override
|
||||
double yAxisProjection(double input) {
|
||||
|
||||
input = Math.min(Math.max(input, -89.5), 89.5);
|
||||
double earthDimensionalRateNormalized = 1.0 - Math.pow(RADIUS_MINOR / RADIUS_MAJOR, 2);
|
||||
|
||||
double inputOnEarthProj = Math.sqrt(earthDimensionalRateNormalized) * Math.sin( Math.toRadians(input));
|
||||
|
||||
inputOnEarthProj = Math.pow(((1.0 - inputOnEarthProj)/(1.0+inputOnEarthProj)), 0.5 * Math.sqrt(earthDimensionalRateNormalized));
|
||||
double inputOnEarthProjNormalized = Math.tan(0.5 * ((Math.PI*0.5) - Math.toRadians(input)))/inputOnEarthProj;
|
||||
return (-1) * RADIUS_MAJOR * Math.log(inputOnEarthProjNormalized);
|
||||
}
|
||||
|
||||
@Override
|
||||
double xAxisProjection(double input) {
|
||||
return RADIUS_MAJOR * Math.toRadians(input);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
package com.baeldung.algorithms.mercator;
|
||||
|
||||
abstract class Mercator {
|
||||
final static double RADIUS_MAJOR = 6378137.0;
|
||||
final static double RADIUS_MINOR = 6356752.3142;
|
||||
|
||||
abstract double yAxisProjection(double input);
|
||||
|
||||
abstract double xAxisProjection(double input);
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package com.baeldung.algorithms.mercator;
|
||||
|
||||
public class SphericalMercator extends Mercator {
|
||||
|
||||
@Override
|
||||
double xAxisProjection(double input) {
|
||||
return Math.toRadians(input) * RADIUS_MAJOR;
|
||||
}
|
||||
|
||||
@Override
|
||||
double yAxisProjection(double input) {
|
||||
return Math.log(Math.tan(Math.PI / 4 + Math.toRadians(input) / 2)) * RADIUS_MAJOR;
|
||||
}
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package com.java.src;
|
||||
package com.baeldung.algorithms.roundedup;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
package com.baeldung.algorithms.mercator;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
|
||||
public class EllipticalMercatorUnitTest {
|
||||
|
||||
@Test
|
||||
public void giventThatTheInputIs22_whenXAxisProjectionIsCalled_thenTheResultIsTheCorrectOne() {
|
||||
Mercator mercator = new EllipticalMercator();
|
||||
double result = mercator.xAxisProjection(22);
|
||||
Assert.assertEquals(result, 2449028.7974520186, 0.0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void giventThatTheInputIs44_whenYAxisProjectionIsCalled_thenTheResultIsTheCorrectOne() {
|
||||
Mercator mercator = new EllipticalMercator();
|
||||
double result = mercator.yAxisProjection(44);
|
||||
Assert.assertEquals(result, 5435749.887511954, 0.0);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
package com.baeldung.algorithms.mercator;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class SphericalMercatorUnitTest {
|
||||
|
||||
@Test
|
||||
public void giventThatTheInputIs22_whenXAxisProjectionIsCalled_thenTheResultIsTheCorrectOne() {
|
||||
Mercator mercator = new SphericalMercator();
|
||||
double result = mercator.xAxisProjection(22);
|
||||
Assert.assertEquals(result, 2449028.7974520186, 0.0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void giventThatTheInputIs44_whenYAxisProjectionIsCalled_thenTheResultIsTheCorrectOne() {
|
||||
Mercator mercator = new SphericalMercator();
|
||||
double result = mercator.yAxisProjection(44);
|
||||
Assert.assertEquals(result, 5465442.183322753, 0.0);
|
||||
}
|
||||
}
|
|
@ -1,10 +1,10 @@
|
|||
package com.java.src;
|
||||
package com.baeldung.algorithms.roundedup;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class RoundUpToHundredTest {
|
||||
public class RoundUpToHundredUnitTest {
|
||||
@Test
|
||||
public void givenInput_whenRound_thenRoundUpToTheNearestHundred() {
|
||||
assertEquals("Rounded up to hundred", 100, RoundUpToHundred.round(99));
|
|
@ -4,4 +4,4 @@
|
|||
- [Merge Sort in Java](https://www.baeldung.com/java-merge-sort)
|
||||
- [Quicksort Algorithm Implementation in Java](https://www.baeldung.com/java-quicksort)
|
||||
- [Insertion Sort in Java](https://www.baeldung.com/java-insertion-sort)
|
||||
|
||||
- [Heap Sort in Java](https://www.baeldung.com/java-heap-sort)
|
||||
|
|
|
@ -1 +0,0 @@
|
|||
/bin/
|
|
@ -1,20 +0,0 @@
|
|||
package com.java.src;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
public class RoundUpToHundred {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
double input = scanner.nextDouble();
|
||||
scanner.close();
|
||||
|
||||
RoundUpToHundred.round(input);
|
||||
}
|
||||
|
||||
static long round(double input) {
|
||||
long i = (long) Math.ceil(input);
|
||||
return ((i + 99) / 100) * 100;
|
||||
};
|
||||
|
||||
}
|
|
@ -1,14 +0,0 @@
|
|||
package com.java.src;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class RoundUpToHundredTest {
|
||||
@Test
|
||||
public void givenInput_whenRound_thenRoundUpToTheNearestHundred() {
|
||||
assertEquals("Rounded up to hundred", 100, RoundUpToHundred.round(99));
|
||||
assertEquals("Rounded up to three hundred ", 300, RoundUpToHundred.round(200.2));
|
||||
assertEquals("Returns same rounded value", 400, RoundUpToHundred.round(400));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
### Relevant Articles:
|
||||
|
||||
- [Introduction to Apache Pulsar](https://www.baeldung.com/apache-pulsar)
|
|
@ -1,38 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>flyway-cdi</artifactId>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>cdi-portable-extension</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>javax.enterprise</groupId>
|
||||
<artifactId>cdi-api</artifactId>
|
||||
<version>2.0.SP1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.flywaydb</groupId>
|
||||
<artifactId>flyway-core</artifactId>
|
||||
<version>5.1.4</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.tomcat</groupId>
|
||||
<artifactId>tomcat-jdbc</artifactId>
|
||||
<version>8.5.33</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.annotation</groupId>
|
||||
<artifactId>javax.annotation-api</artifactId>
|
||||
<version>1.3.2</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
|
@ -1,74 +0,0 @@
|
|||
package com.baeldung.cdi.extension;
|
||||
|
||||
import org.apache.tomcat.jdbc.pool.DataSource;
|
||||
import org.flywaydb.core.Flyway;
|
||||
|
||||
import javax.annotation.sql.DataSourceDefinition;
|
||||
import javax.enterprise.context.ApplicationScoped;
|
||||
import javax.enterprise.event.Observes;
|
||||
import javax.enterprise.inject.Any;
|
||||
import javax.enterprise.inject.Default;
|
||||
import javax.enterprise.inject.literal.InjectLiteral;
|
||||
import javax.enterprise.inject.spi.*;
|
||||
import javax.enterprise.util.AnnotationLiteral;
|
||||
|
||||
|
||||
/**
|
||||
* Flyway is now under CDI container like:
|
||||
*
|
||||
* @ApplicationScoped
|
||||
* @FlywayType public class Flyway{
|
||||
* @Inject setDataSource(DataSource dataSource){
|
||||
* //...
|
||||
* }
|
||||
* }
|
||||
*/
|
||||
|
||||
public class FlywayExtension implements Extension {
|
||||
|
||||
DataSourceDefinition dataSourceDefinition = null;
|
||||
|
||||
public void registerFlywayType(@Observes BeforeBeanDiscovery bbdEvent) {
|
||||
bbdEvent.addAnnotatedType(Flyway.class, Flyway.class.getName());
|
||||
}
|
||||
|
||||
public void detectDataSourceDefinition(@Observes @WithAnnotations(DataSourceDefinition.class) ProcessAnnotatedType<?> patEvent) {
|
||||
AnnotatedType at = patEvent.getAnnotatedType();
|
||||
dataSourceDefinition = at.getAnnotation(DataSourceDefinition.class);
|
||||
}
|
||||
|
||||
public void processAnnotatedType(@Observes ProcessAnnotatedType<Flyway> patEvent) {
|
||||
patEvent.configureAnnotatedType()
|
||||
//Add Scope
|
||||
.add(ApplicationScoped.Literal.INSTANCE)
|
||||
//Add Qualifier
|
||||
.add(new AnnotationLiteral<FlywayType>() {
|
||||
})
|
||||
//Decorate setDataSource(DataSource dataSource){} with @Inject
|
||||
.filterMethods(annotatedMethod -> {
|
||||
return annotatedMethod.getParameters().size() == 1 &&
|
||||
annotatedMethod.getParameters().get(0).getBaseType().equals(javax.sql.DataSource.class);
|
||||
})
|
||||
.findFirst().get().add(InjectLiteral.INSTANCE);
|
||||
}
|
||||
|
||||
void afterBeanDiscovery(@Observes AfterBeanDiscovery abdEvent, BeanManager bm) {
|
||||
abdEvent.addBean()
|
||||
.types(javax.sql.DataSource.class, DataSource.class)
|
||||
.qualifiers(new AnnotationLiteral<Default>() {}, new AnnotationLiteral<Any>() {})
|
||||
.scope(ApplicationScoped.class)
|
||||
.name(DataSource.class.getName())
|
||||
.beanClass(DataSource.class)
|
||||
.createWith(creationalContext -> {
|
||||
DataSource instance = new DataSource();
|
||||
instance.setUrl(dataSourceDefinition.url());
|
||||
instance.setDriverClassName(dataSourceDefinition.className());
|
||||
return instance;
|
||||
});
|
||||
}
|
||||
|
||||
void runFlywayMigration(@Observes AfterDeploymentValidation adv, BeanManager manager) {
|
||||
Flyway flyway = manager.createInstance().select(Flyway.class, new AnnotationLiteral<FlywayType>() {}).get();
|
||||
flyway.migrate();
|
||||
}
|
||||
}
|
|
@ -1,14 +0,0 @@
|
|||
package com.baeldung.cdi.extension;
|
||||
|
||||
import javax.inject.Qualifier;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
import static java.lang.annotation.ElementType.*;
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target({FIELD, METHOD, PARAMETER, TYPE})
|
||||
@Qualifier
|
||||
public @interface FlywayType {
|
||||
}
|
|
@ -1,6 +0,0 @@
|
|||
<beans version="2.0" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
|
||||
http://xmlns.jcp.org/xml/ns/javaee/beans_2_0.xsd"
|
||||
bean-discovery-mode="annotated">
|
||||
</beans>
|
|
@ -1,2 +0,0 @@
|
|||
com.baeldung.cdi.extension.FlywayExtension
|
||||
|
|
@ -1,52 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>main-app</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>cdi-portable-extension</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>javax.enterprise</groupId>
|
||||
<artifactId>cdi-api</artifactId>
|
||||
<version>2.0.SP1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jboss.weld.se</groupId>
|
||||
<artifactId>weld-se-core</artifactId>
|
||||
<version>3.0.5.Final</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>flyway-cdi</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>1.4.197</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>javax.annotation</groupId>
|
||||
<artifactId>javax.annotation-api</artifactId>
|
||||
<version>1.3.2</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
</project>
|
|
@ -1,16 +0,0 @@
|
|||
package com.baeldung.cdi.extension;
|
||||
|
||||
import javax.annotation.sql.DataSourceDefinition;
|
||||
import javax.enterprise.context.ApplicationScoped;
|
||||
import javax.enterprise.inject.se.SeContainer;
|
||||
import javax.enterprise.inject.se.SeContainerInitializer;
|
||||
|
||||
@ApplicationScoped
|
||||
@DataSourceDefinition(name = "ds", className = "org.h2.Driver", url = "jdbc:h2:mem:testdb")
|
||||
public class MainApp {
|
||||
public static void main(String[] args) {
|
||||
SeContainerInitializer initializer = SeContainerInitializer.newInstance();
|
||||
try (SeContainer container = initializer.initialize()) {
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,6 +0,0 @@
|
|||
<beans version="2.0" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
|
||||
http://xmlns.jcp.org/xml/ns/javaee/beans_2_0.xsd"
|
||||
bean-discovery-mode="annotated">
|
||||
</beans>
|
|
@ -1,4 +0,0 @@
|
|||
create table PERSON (
|
||||
ID int not null,
|
||||
NAME varchar(100) not null
|
||||
);
|
|
@ -1,3 +0,0 @@
|
|||
insert into PERSON (ID, NAME) values (1, 'Axel');
|
||||
insert into PERSON (ID, NAME) values (2, 'Mr. Foo');
|
||||
insert into PERSON (ID, NAME) values (3, 'Ms. Bar');
|
|
@ -1,30 +0,0 @@
|
|||
<?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>cdi-portable-extension</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
</properties>
|
||||
|
||||
<modules>
|
||||
<module>main-app</module>
|
||||
<module>flyway-cdi</module>
|
||||
</modules>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>javax.enterprise</groupId>
|
||||
<artifactId>cdi-api</artifactId>
|
||||
<version>2.0.SP1</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.reducingIfElse;
|
||||
|
||||
public class AddCommand implements Command {
|
||||
|
||||
private int a;
|
||||
private int b;
|
||||
|
||||
public AddCommand(int a, int b) {
|
||||
this.a = a;
|
||||
this.b = b;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Integer execute() {
|
||||
return a + b;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
package com.baeldung.reducingIfElse;
|
||||
|
||||
public class AddRule implements Rule {
|
||||
|
||||
private int result;
|
||||
|
||||
@Override
|
||||
public boolean evaluate(Expression expression) {
|
||||
boolean evalResult = false;
|
||||
if (expression.getOperator() == Operator.ADD) {
|
||||
this.result = expression.getX() + expression.getY();
|
||||
evalResult = true;
|
||||
}
|
||||
return evalResult;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Result getResult() {
|
||||
return new Result(result);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
package com.baeldung.reducingIfElse;
|
||||
|
||||
public class Addition implements Operation {
|
||||
@Override
|
||||
public int apply(int a, int b) {
|
||||
return a + b;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,83 @@
|
|||
package com.baeldung.reducingIfElse;
|
||||
|
||||
public class Calculator {
|
||||
|
||||
public int calculate(int a, int b, String operator) {
|
||||
int result = Integer.MIN_VALUE;
|
||||
|
||||
if ("add".equals(operator)) {
|
||||
result = a + b;
|
||||
} else if ("multiply".equals(operator)) {
|
||||
result = a * b;
|
||||
} else if ("divide".equals(operator)) {
|
||||
result = a / b;
|
||||
} else if ("subtract".equals(operator)) {
|
||||
result = a - b;
|
||||
} else if ("modulo".equals(operator)) {
|
||||
result = a % b;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public int calculateUsingSwitch(int a, int b, String operator) {
|
||||
int result = 0;
|
||||
switch (operator) {
|
||||
case "add":
|
||||
result = a + b;
|
||||
break;
|
||||
case "multiply":
|
||||
result = a * b;
|
||||
break;
|
||||
case "divide":
|
||||
result = a / b;
|
||||
break;
|
||||
case "subtract":
|
||||
result = a - b;
|
||||
break;
|
||||
case "modulo":
|
||||
result = a % b;
|
||||
break;
|
||||
default:
|
||||
result = Integer.MIN_VALUE;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public int calculateUsingSwitch(int a, int b, Operator operator) {
|
||||
int result = 0;
|
||||
switch (operator) {
|
||||
case ADD:
|
||||
result = a + b;
|
||||
break;
|
||||
case MULTIPLY:
|
||||
result = a * b;
|
||||
break;
|
||||
case DIVIDE:
|
||||
result = a / b;
|
||||
break;
|
||||
case SUBTRACT:
|
||||
result = a - b;
|
||||
break;
|
||||
case MODULO:
|
||||
result = a % b;
|
||||
break;
|
||||
default:
|
||||
result = Integer.MIN_VALUE;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public int calculate(int a, int b, Operator operator) {
|
||||
return operator.apply(a, b);
|
||||
}
|
||||
|
||||
public int calculateUsingFactory(int a, int b, String operation) {
|
||||
Operation targetOperation = OperatorFactory.getOperation(operation)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Invalid Operator"));
|
||||
return targetOperation.apply(a, b);
|
||||
}
|
||||
|
||||
public int calculate(Command command) {
|
||||
return command.execute();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
package com.baeldung.reducingIfElse;
|
||||
|
||||
public interface Command {
|
||||
Integer execute();
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
package com.baeldung.reducingIfElse;
|
||||
|
||||
public class Division implements Operation {
|
||||
@Override public int apply(int a, int b) {
|
||||
return a / b;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,26 @@
|
|||
package com.baeldung.reducingIfElse;
|
||||
|
||||
public class Expression {
|
||||
|
||||
private Integer x;
|
||||
private Integer y;
|
||||
private Operator operator;
|
||||
|
||||
public Expression(Integer x, Integer y, Operator operator) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
this.operator = operator;
|
||||
}
|
||||
|
||||
public Integer getX() {
|
||||
return x;
|
||||
}
|
||||
|
||||
public Integer getY() {
|
||||
return y;
|
||||
}
|
||||
|
||||
public Operator getOperator() {
|
||||
return operator;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
package com.baeldung.reducingIfElse;
|
||||
|
||||
public class Modulo implements Operation {
|
||||
@Override public int apply(int a, int b) {
|
||||
return a % b;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
package com.baeldung.reducingIfElse;
|
||||
|
||||
public class Multiplication implements Operation {
|
||||
@Override public int apply(int a, int b) {
|
||||
return 0;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
package com.baeldung.reducingIfElse;
|
||||
|
||||
public interface Operation {
|
||||
int apply(int a, int b);
|
||||
}
|
|
@ -0,0 +1,41 @@
|
|||
package com.baeldung.reducingIfElse;
|
||||
|
||||
public enum Operator {
|
||||
|
||||
ADD {
|
||||
@Override
|
||||
public int apply(int a, int b) {
|
||||
return a + b;
|
||||
}
|
||||
},
|
||||
|
||||
MULTIPLY {
|
||||
@Override
|
||||
public int apply(int a, int b) {
|
||||
return a * b;
|
||||
}
|
||||
},
|
||||
|
||||
SUBTRACT {
|
||||
@Override
|
||||
public int apply(int a, int b) {
|
||||
return a - b;
|
||||
}
|
||||
},
|
||||
|
||||
DIVIDE {
|
||||
@Override
|
||||
public int apply(int a, int b) {
|
||||
return a / b;
|
||||
}
|
||||
},
|
||||
|
||||
MODULO {
|
||||
@Override
|
||||
public int apply(int a, int b) {
|
||||
return a % b;
|
||||
}
|
||||
};
|
||||
|
||||
public abstract int apply(int a, int b);
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
package com.baeldung.reducingIfElse;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
public class OperatorFactory {
|
||||
|
||||
static Map<String, Operation> operationMap = new HashMap<>();
|
||||
static {
|
||||
operationMap.put("add", new Addition());
|
||||
operationMap.put("divide", new Division());
|
||||
operationMap.put("multiply", new Multiplication());
|
||||
operationMap.put("subtract", new Subtraction());
|
||||
operationMap.put("modulo", new Modulo());
|
||||
}
|
||||
|
||||
public static Optional<Operation> getOperation(String operation) {
|
||||
return Optional.ofNullable(operationMap.get(operation));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
package com.baeldung.reducingIfElse;
|
||||
|
||||
public class Result {
|
||||
int value;
|
||||
|
||||
public Result(int value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public int getValue() {
|
||||
return value;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
package com.baeldung.reducingIfElse;
|
||||
|
||||
public interface Rule {
|
||||
|
||||
boolean evaluate(Expression expression);
|
||||
|
||||
Result getResult();
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
package com.baeldung.reducingIfElse;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class RuleEngine {
|
||||
|
||||
private static List<Rule> rules = new ArrayList<>();
|
||||
|
||||
static {
|
||||
rules.add(new AddRule());
|
||||
}
|
||||
|
||||
public Result process(Expression expression) {
|
||||
|
||||
Rule rule = rules.stream()
|
||||
.filter(r -> r.evaluate(expression))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new IllegalArgumentException("Expression does not matches any Rule"));
|
||||
return rule.getResult();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
package com.baeldung.reducingIfElse;
|
||||
|
||||
public class Subtraction implements Operation {
|
||||
@Override public int apply(int a, int b) {
|
||||
return a - b;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
package com.baeldung.reduceIfelse;
|
||||
|
||||
import com.baeldung.reducingIfElse.AddCommand;
|
||||
import com.baeldung.reducingIfElse.Calculator;
|
||||
import com.baeldung.reducingIfElse.Operator;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class CalculatorUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenCalculateUsingStringOperator_thenReturnCorrectResult() {
|
||||
Calculator calculator = new Calculator();
|
||||
int result = calculator.calculate(3, 4, "add");
|
||||
assertEquals(7, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCalculateUsingEnumOperator_thenReturnCorrectResult() {
|
||||
Calculator calculator = new Calculator();
|
||||
int result = calculator.calculate(3, 4, Operator.valueOf("ADD"));
|
||||
assertEquals(7, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCalculateUsingCommand_thenReturnCorrectResult() {
|
||||
Calculator calculator = new Calculator();
|
||||
int result = calculator.calculate(new AddCommand(3, 7));
|
||||
assertEquals(10, result);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
package com.baeldung.reduceIfelse;
|
||||
|
||||
import com.baeldung.reducingIfElse.Expression;
|
||||
import com.baeldung.reducingIfElse.Operator;
|
||||
import com.baeldung.reducingIfElse.Result;
|
||||
import com.baeldung.reducingIfElse.RuleEngine;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
public class RuleEngineUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenNumbersGivenToRuleEngine_thenReturnCorrectResult() {
|
||||
Expression expression = new Expression(5, 5, Operator.ADD);
|
||||
RuleEngine engine = new RuleEngine();
|
||||
Result result = engine.process(expression);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(10, result.getValue());
|
||||
}
|
||||
}
|
|
@ -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
|
|
@ -0,0 +1,15 @@
|
|||
=========
|
||||
|
||||
## Core Java Arrays Cookbooks and Examples
|
||||
|
||||
### Relevant Articles:
|
||||
- [How to Copy an Array in Java](http://www.baeldung.com/java-array-copy)
|
||||
- [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)
|
||||
- [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)
|
||||
- [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)
|
||||
- [How to Invert an Array in Java](http://www.baeldung.com/java-invert-array)
|
||||
- [Array Operations in Java](http://www.baeldung.com/java-common-array-operations)
|
||||
|
|
@ -0,0 +1,412 @@
|
|||
<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</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>core-java-arrays</name>
|
||||
|
||||
<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>
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>${log4j.version}</version>
|
||||
</dependency>
|
||||
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>log4j-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
<!-- test scoped -->
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj-core.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>${jmh-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${jmh-generator-annprocess.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-web</artifactId>
|
||||
<version>${springframework.spring-web.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-arrays</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
<exclude>**/*IntegrationTest.java</exclude>
|
||||
<exclude>**/*IntTest.java</exclude>
|
||||
<exclude>**/*LongRunningUnitTest.java</exclude>
|
||||
<exclude>**/*ManualTest.java</exclude>
|
||||
</excludes>
|
||||
<testFailureIgnore>true</testFailureIgnore>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>copy-dependencies</id>
|
||||
<phase>prepare-package</phase>
|
||||
<goals>
|
||||
<goal>copy-dependencies</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<outputDirectory>${project.build.directory}/libs</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<version>${maven-jar-plugin.version}</version>
|
||||
<configuration>
|
||||
<archive>
|
||||
<manifest>
|
||||
<addClasspath>true</addClasspath>
|
||||
<classpathPrefix>libs/</classpathPrefix>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-assembly-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>single</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<archiveBaseDirectory>${project.basedir}</archiveBaseDirectory>
|
||||
<archive>
|
||||
<manifest>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
<descriptorRefs>
|
||||
<descriptorRef>jar-with-dependencies</descriptorRef>
|
||||
</descriptorRefs>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<version>${maven-shade-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>shade</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<shadedArtifactAttached>true</shadedArtifactAttached>
|
||||
<transformers>
|
||||
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</transformer>
|
||||
</transformers>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>com.jolira</groupId>
|
||||
<artifactId>onejar-maven-plugin</artifactId>
|
||||
<version>${onejar-maven-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<configuration>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
<attachToBuild>true</attachToBuild>
|
||||
<filename>${project.build.finalName}-onejar.${project.packaging}</filename>
|
||||
</configuration>
|
||||
<goals>
|
||||
<goal>one-jar</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<version>${spring-boot-maven-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>repackage</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<classifier>spring-boot</classifier>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>${exec-maven-plugin.version}</version>
|
||||
<configuration>
|
||||
<executable>java</executable>
|
||||
<mainClass>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</mainClass>
|
||||
<arguments>
|
||||
<argument>-Xmx300m</argument>
|
||||
<argument>-XX:+UseParallelGC</argument>
|
||||
<argument>-classpath</argument>
|
||||
<classpath />
|
||||
<argument>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</argument>
|
||||
</arguments>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-javadoc-plugin</artifactId>
|
||||
<version>${maven-javadoc-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>integration</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>integration-test</phase>
|
||||
<goals>
|
||||
<goal>test</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/*ManualTest.java</exclude>
|
||||
</excludes>
|
||||
<includes>
|
||||
<include>**/*IntegrationTest.java</include>
|
||||
<include>**/*IntTest.java</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
<configuration>
|
||||
<systemPropertyVariables>
|
||||
<test.mime>json</test.mime>
|
||||
</systemPropertyVariables>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>${exec-maven-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>run-benchmarks</id>
|
||||
<!-- <phase>integration-test</phase> -->
|
||||
<phase>none</phase>
|
||||
<goals>
|
||||
<goal>exec</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<classpathScope>test</classpathScope>
|
||||
<executable>java</executable>
|
||||
<arguments>
|
||||
<argument>-classpath</argument>
|
||||
<classpath />
|
||||
<argument>org.openjdk.jmh.Main</argument>
|
||||
<argument>.*</argument>
|
||||
</arguments>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
|
||||
<!-- java instrumentation profiles to build jars -->
|
||||
<profile>
|
||||
<id>buildAgentLoader</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>jar</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<classifier>agentLoader</classifier>
|
||||
<classesDirectory>target/classes</classesDirectory>
|
||||
<archive>
|
||||
<manifest>
|
||||
<addClasspath>true</addClasspath>
|
||||
</manifest>
|
||||
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
|
||||
</archive>
|
||||
|
||||
<includes>
|
||||
<include>com/baeldung/instrumentation/application/AgentLoader.class</include>
|
||||
<include>com/baeldung/instrumentation/application/Launcher.class</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
<profile>
|
||||
<id>buildApplication</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>jar</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<classifier>application</classifier>
|
||||
<classesDirectory>target/classes</classesDirectory>
|
||||
<archive>
|
||||
<manifest>
|
||||
<addClasspath>true</addClasspath>
|
||||
</manifest>
|
||||
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
|
||||
</archive>
|
||||
|
||||
<includes>
|
||||
<include>com/baeldung/instrumentation/application/MyAtm.class</include>
|
||||
<include>com/baeldung/instrumentation/application/MyAtmApplication.class</include>
|
||||
<include>com/baeldung/instrumentation/application/Launcher.class</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
<profile>
|
||||
<id>buildAgent</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>jar</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<classifier>agent</classifier>
|
||||
<classesDirectory>target/classes</classesDirectory>
|
||||
<archive>
|
||||
<manifest>
|
||||
<addClasspath>true</addClasspath>
|
||||
</manifest>
|
||||
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
|
||||
</archive>
|
||||
|
||||
<includes>
|
||||
<include>com/baeldung/instrumentation/agent/AtmTransformer.class</include>
|
||||
<include>com/baeldung/instrumentation/agent/MyInstrumentationAgent.class</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
<properties>
|
||||
|
||||
<!-- util -->
|
||||
<commons-lang3.version>3.8.1</commons-lang3.version>
|
||||
<lombok.version>1.16.12</lombok.version>
|
||||
|
||||
<jmh-core.version>1.19</jmh-core.version>
|
||||
<jmh-generator-annprocess.version>1.19</jmh-generator-annprocess.version>
|
||||
|
||||
<!-- testing -->
|
||||
<assertj-core.version>3.10.0</assertj-core.version>
|
||||
|
||||
<!-- maven and spring plugins -->
|
||||
<maven-surefire-plugin.version>2.21.0</maven-surefire-plugin.version>
|
||||
<springframework.spring-web.version>4.3.4.RELEASE</springframework.spring-web.version>
|
||||
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
|
||||
<maven-jar-plugin.version>3.0.2</maven-jar-plugin.version>
|
||||
<onejar-maven-plugin.version>1.4.4</onejar-maven-plugin.version>
|
||||
<maven-shade-plugin.version>3.1.1</maven-shade-plugin.version>
|
||||
<spring-boot-maven-plugin.version>2.0.3.RELEASE</spring-boot-maven-plugin.version>
|
||||
<exec-maven-plugin.version>1.6.0</exec-maven-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -2,7 +2,7 @@ package com.baeldung.array;
|
|||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.apache.commons.lang.ArrayUtils;
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
|
||||
public class ArrayInitializer {
|
||||
|
|
@ -0,0 +1,197 @@
|
|||
package com.baeldung.array.operations;
|
||||
|
||||
import java.lang.reflect.Array;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Random;
|
||||
import java.util.Set;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.IntPredicate;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
|
||||
public class ArrayOperations {
|
||||
|
||||
// Get the first and last item of an array
|
||||
public static <T> T getFirstObject(T[] array) {
|
||||
return array[0];
|
||||
}
|
||||
|
||||
public static int getFirstInt(int[] array) {
|
||||
return array[0];
|
||||
}
|
||||
|
||||
public static <T> T getLastObject(T[] array) {
|
||||
return array[array.length - 1];
|
||||
}
|
||||
|
||||
public static int getLastInt(int[] array) {
|
||||
return array[array.length - 1];
|
||||
}
|
||||
|
||||
// Append a new item to an array
|
||||
public static <T> T[] appendObject(T[] array, T newItem) {
|
||||
return ArrayUtils.add(array, newItem);
|
||||
}
|
||||
|
||||
public static int[] appendInt(int[] array, int newItem) {
|
||||
int[] newArray = Arrays.copyOf(array, array.length + 1);
|
||||
newArray[newArray.length - 1] = newItem;
|
||||
return newArray;
|
||||
}
|
||||
|
||||
public static int[] appendIntWithUtils(int[] array, int newItem) {
|
||||
return ArrayUtils.add(array, newItem);
|
||||
}
|
||||
|
||||
// Compare two arrays to check if they have the same elements
|
||||
public static <T> boolean compareObjectArrays(T[] array1, T[] array2) {
|
||||
return Arrays.equals(array1, array2);
|
||||
}
|
||||
|
||||
public static boolean compareIntArrays(int[] array1, int[] array2) {
|
||||
return Arrays.equals(array1, array2);
|
||||
}
|
||||
|
||||
// Deep Compare (for nested arrays)
|
||||
public static <T> boolean deepCompareObjectArrayUsingArrays(T[][] array1, T[][] array2) {
|
||||
// We can use Objects.deepEquals for a broader approach
|
||||
return Arrays.deepEquals(array1, array2);
|
||||
}
|
||||
|
||||
public static boolean deepCompareIntArrayUsingArrays(int[][] array1, int[][] array2) {
|
||||
return Arrays.deepEquals(array1, array2);
|
||||
}
|
||||
|
||||
// Check if array is empty
|
||||
public static <T> boolean isEmptyObjectArrayUsingUtils(T[] array1) {
|
||||
return ArrayUtils.isEmpty(array1);
|
||||
}
|
||||
|
||||
public static boolean isEmptyIntArrayUsingUtils(int[] array1) {
|
||||
return ArrayUtils.isEmpty(array1);
|
||||
}
|
||||
|
||||
// Remove duplicates
|
||||
public static Integer[] removeDuplicateObjects(Integer[] array) {
|
||||
// We can use other ways of converting the array to a set too
|
||||
Set<Integer> set = new HashSet<>(Arrays.asList(array));
|
||||
return set.toArray(new Integer[set.size()]);
|
||||
}
|
||||
|
||||
public static int[] removeDuplicateInts(int[] array) {
|
||||
// Box
|
||||
Integer[] list = ArrayUtils.toObject(array);
|
||||
// Remove duplicates
|
||||
Set<Integer> set = new HashSet<Integer>(Arrays.asList(list));
|
||||
// Create array and unbox
|
||||
return ArrayUtils.toPrimitive(set.toArray(new Integer[set.size()]));
|
||||
}
|
||||
|
||||
// Remove duplicates preserving the order
|
||||
public static Integer[] removeDuplicateWithOrderObjectArray(Integer[] array) {
|
||||
// We can use other ways of converting the array to a set too
|
||||
Set<Integer> set = new LinkedHashSet<>(Arrays.asList(array));
|
||||
return set.toArray(new Integer[set.size()]);
|
||||
}
|
||||
|
||||
public static int[] removeDuplicateWithOrderIntArray(int[] array) {
|
||||
// Box
|
||||
Integer[] list = ArrayUtils.toObject(array);
|
||||
// Remove duplicates
|
||||
Set<Integer> set = new LinkedHashSet<Integer>(Arrays.asList(list));
|
||||
// Create array and unbox
|
||||
return ArrayUtils.toPrimitive(set.toArray(new Integer[set.size()]));
|
||||
}
|
||||
|
||||
// Print an array
|
||||
public static String printObjectArray(Integer[] array) {
|
||||
return ArrayUtils.toString(array);
|
||||
}
|
||||
|
||||
public static String printObjectArray(Integer[][] array) {
|
||||
return ArrayUtils.toString(array);
|
||||
}
|
||||
|
||||
public static String printIntArray(int[] array) {
|
||||
return ArrayUtils.toString(array);
|
||||
}
|
||||
|
||||
public static String printIntArray(int[][] array) {
|
||||
return ArrayUtils.toString(array);
|
||||
}
|
||||
|
||||
// Box or Unbox values
|
||||
public static int[] unboxIntegerArray(Integer[] array) {
|
||||
return ArrayUtils.toPrimitive(array);
|
||||
}
|
||||
|
||||
public static Integer[] boxIntArray(int[] array) {
|
||||
return ArrayUtils.toObject(array);
|
||||
}
|
||||
|
||||
// Map array values
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T, U> U[] mapObjectArray(T[] array, Function<T, U> function, Class<U> targetClazz) {
|
||||
U[] newArray = (U[]) Array.newInstance(targetClazz, array.length);
|
||||
for (int i = 0; i < array.length; i++) {
|
||||
newArray[i] = function.apply(array[i]);
|
||||
}
|
||||
return newArray;
|
||||
}
|
||||
|
||||
public static String[] mapIntArrayToString(int[] array) {
|
||||
return Arrays.stream(array)
|
||||
.mapToObj(value -> String.format("Value: %s", value))
|
||||
.toArray(String[]::new);
|
||||
}
|
||||
|
||||
// Filter array values
|
||||
public static Integer[] filterObjectArray(Integer[] array, Predicate<Integer> predicate) {
|
||||
return Arrays.stream(array)
|
||||
.filter(predicate)
|
||||
.toArray(Integer[]::new);
|
||||
}
|
||||
|
||||
public static int[] filterIntArray(int[] array, IntPredicate predicate) {
|
||||
return Arrays.stream(array)
|
||||
.filter(predicate)
|
||||
.toArray();
|
||||
}
|
||||
|
||||
// Insert item between others
|
||||
public static int[] insertBetweenIntArray(int[] array, int... values) {
|
||||
return ArrayUtils.insert(2, array, values);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T> T[] insertBetweenObjectArray(T[] array, T... values) {
|
||||
return ArrayUtils.insert(2, array, values);
|
||||
}
|
||||
|
||||
// Shuffling arrays
|
||||
public static int[] shuffleIntArray(int[] array) {
|
||||
// we create a different array instance for testing purposes
|
||||
int[] shuffled = Arrays.copyOf(array, array.length);
|
||||
ArrayUtils.shuffle(shuffled);
|
||||
return shuffled;
|
||||
}
|
||||
|
||||
public static <T> T[] shuffleObjectArray(T[] array) {
|
||||
// we create a different array instance for testing purposes
|
||||
T[] shuffled = Arrays.copyOf(array, array.length);
|
||||
ArrayUtils.shuffle(shuffled);
|
||||
return shuffled;
|
||||
}
|
||||
|
||||
// Get random number
|
||||
public static int getRandomFromIntArray(int[] array) {
|
||||
return array[new Random().nextInt(array.length)];
|
||||
}
|
||||
|
||||
public static <T> T getRandomFromObjectArray(T[] array) {
|
||||
return array[new Random().nextInt(array.length)];
|
||||
}
|
||||
}
|
|
@ -0,0 +1,365 @@
|
|||
package com.baeldung.array.operations;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.assertj.core.api.Condition;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class ArrayOperationsUnitTest {
|
||||
|
||||
private Integer[] defaultObjectArray;
|
||||
private int[] defaultIntArray;
|
||||
private Integer[][] defaultJaggedObjectArray;
|
||||
private int[][] defaultJaggedIntArray;
|
||||
|
||||
@BeforeEach
|
||||
public void setupDefaults() {
|
||||
defaultObjectArray = new Integer[] { 3, 5, 2, 5, 14, 4 };
|
||||
defaultIntArray = new int[] { 3, 5, 2, 5, 14, 4 };
|
||||
defaultJaggedObjectArray = new Integer[][] { { 1, 3 }, { 5 }, {} };
|
||||
defaultJaggedIntArray = new int[][] { { 1, 3 }, { 5 }, {} };
|
||||
}
|
||||
|
||||
// Get the first and last item of an array
|
||||
@Test
|
||||
public void whenGetFirstObjectCalled_thenReturnFirstItemOfArray() {
|
||||
Integer output = ArrayOperations.getFirstObject(defaultObjectArray);
|
||||
|
||||
assertThat(output).isEqualTo(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetFirstIntCalled_thenReturnFirstItemOfArray() {
|
||||
int output = ArrayOperations.getFirstInt(defaultIntArray);
|
||||
|
||||
assertThat(output).isEqualTo(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetLastObjectCalled_thenReturnLastItemOfArray() {
|
||||
Integer output = ArrayOperations.getLastObject(defaultObjectArray);
|
||||
|
||||
assertThat(output).isEqualTo(4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetLastIntCalled_thenReturnLastItemOfArray() {
|
||||
int output = ArrayOperations.getLastInt(defaultIntArray);
|
||||
|
||||
assertThat(output).isEqualTo(4);
|
||||
}
|
||||
|
||||
// Append a new item to an array
|
||||
@Test
|
||||
public void whenAppendObject_thenReturnArrayWithExtraItem() {
|
||||
Integer[] output = ArrayOperations.appendObject(defaultObjectArray, 7);
|
||||
|
||||
assertThat(output).endsWith(4, 7)
|
||||
.hasSize(7);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAppendInt_thenReturnArrayWithExtraItem() {
|
||||
int[] output = ArrayOperations.appendInt(defaultIntArray, 7);
|
||||
int[] outputUsingUtils = ArrayOperations.appendIntWithUtils(defaultIntArray, 7);
|
||||
|
||||
assertThat(output).endsWith(4, 7)
|
||||
.hasSize(7);
|
||||
assertThat(outputUsingUtils).endsWith(4, 7)
|
||||
.hasSize(7);
|
||||
}
|
||||
|
||||
// Compare two arrays to check if they have the same elements
|
||||
@Test
|
||||
public void whenCompareObjectArrays_thenReturnBoolean() {
|
||||
Integer[] array2 = { 8, 7, 6 };
|
||||
Integer[] sameArray = { 3, 5, 2, 5, 14, 4 };
|
||||
boolean output = ArrayOperations.compareObjectArrays(defaultObjectArray, array2);
|
||||
boolean output2 = ArrayOperations.compareObjectArrays(defaultObjectArray, sameArray);
|
||||
|
||||
assertThat(output).isFalse();
|
||||
assertThat(output2).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCompareIntArrays_thenReturnBoolean() {
|
||||
int[] array2 = { 8, 7, 6 };
|
||||
int[] sameArray = { 3, 5, 2, 5, 14, 4 };
|
||||
boolean output = ArrayOperations.compareIntArrays(defaultIntArray, array2);
|
||||
boolean output2 = ArrayOperations.compareIntArrays(defaultIntArray, sameArray);
|
||||
|
||||
assertThat(output).isFalse();
|
||||
assertThat(output2).isTrue();
|
||||
}
|
||||
|
||||
// Deep compare
|
||||
@Test
|
||||
public void whenDeepCompareObjectArrays_thenReturnBoolean() {
|
||||
Integer[][] sameArray = { { 1, 3 }, { 5 }, {} };
|
||||
Integer[][] array2 = { { 1, 3 }, { 5 }, { 3 } };
|
||||
boolean output = ArrayOperations.deepCompareObjectArrayUsingArrays(defaultJaggedObjectArray, array2);
|
||||
boolean output2 = ArrayOperations.deepCompareObjectArrayUsingArrays(defaultJaggedObjectArray, sameArray);
|
||||
// Because arrays are Objects, we could wrongly use the non-deep approach
|
||||
boolean outputUsingNonDeep = ArrayOperations.compareObjectArrays(defaultJaggedObjectArray, sameArray);
|
||||
|
||||
assertThat(output).isFalse();
|
||||
assertThat(output2).isTrue();
|
||||
// This is not what we would expect!
|
||||
assertThat(outputUsingNonDeep).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDeepCompareIntArrays_thenReturnBoolean() {
|
||||
int[][] sameArray = { { 1, 3 }, { 5 }, {} };
|
||||
int[][] array2 = { { 1, 3 }, { 5 }, { 3 } };
|
||||
boolean output = ArrayOperations.deepCompareIntArrayUsingArrays(defaultJaggedIntArray, array2);
|
||||
boolean output2 = ArrayOperations.deepCompareIntArrayUsingArrays(defaultJaggedIntArray, sameArray);
|
||||
|
||||
assertThat(output).isFalse();
|
||||
assertThat(output2).isTrue();
|
||||
}
|
||||
|
||||
// Empty Check
|
||||
@Test
|
||||
public void whenIsEmptyObjectArray_thenReturnBoolean() {
|
||||
Integer[] array2 = {};
|
||||
Integer[] array3 = null;
|
||||
Integer[] array4 = { null, null, null };
|
||||
Integer[] array5 = { null };
|
||||
Integer[][] array6 = { {}, {}, {} };
|
||||
boolean output = ArrayOperations.isEmptyObjectArrayUsingUtils(defaultObjectArray);
|
||||
boolean output2 = ArrayOperations.isEmptyObjectArrayUsingUtils(array2);
|
||||
boolean output3 = ArrayOperations.isEmptyObjectArrayUsingUtils(array3);
|
||||
boolean output4 = ArrayOperations.isEmptyObjectArrayUsingUtils(array4);
|
||||
boolean output5 = ArrayOperations.isEmptyObjectArrayUsingUtils(array5);
|
||||
boolean output6 = ArrayOperations.isEmptyObjectArrayUsingUtils(array6);
|
||||
|
||||
assertThat(output).isFalse();
|
||||
assertThat(output2).isTrue();
|
||||
assertThat(output3).isTrue();
|
||||
// Mind these edge cases!
|
||||
assertThat(output4).isFalse();
|
||||
assertThat(output5).isFalse();
|
||||
assertThat(output6).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenIsEmptyIntArray_thenReturnBoolean() {
|
||||
int[] array2 = {};
|
||||
boolean output = ArrayOperations.isEmptyIntArrayUsingUtils(defaultIntArray);
|
||||
boolean output2 = ArrayOperations.isEmptyIntArrayUsingUtils(array2);
|
||||
|
||||
assertThat(output).isFalse();
|
||||
assertThat(output2).isTrue();
|
||||
}
|
||||
|
||||
// Remove Duplicates
|
||||
@Test
|
||||
public void whenRemoveDuplicateObjectArray_thenReturnArrayWithNoDuplicates() {
|
||||
Integer[] output = ArrayOperations.removeDuplicateObjects(defaultObjectArray);
|
||||
|
||||
assertThat(output).containsOnlyOnce(5)
|
||||
.hasSize(5)
|
||||
.doesNotHaveDuplicates();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRemoveDuplicateIntArray_thenReturnArrayWithNoDuplicates() {
|
||||
int[] output = ArrayOperations.removeDuplicateInts(defaultIntArray);
|
||||
|
||||
assertThat(output).containsOnlyOnce(5)
|
||||
.hasSize(5)
|
||||
.doesNotHaveDuplicates();
|
||||
}
|
||||
|
||||
// Remove Duplicates Preserving order
|
||||
@Test
|
||||
public void whenRemoveDuplicatePreservingOrderObjectArray_thenReturnArrayWithNoDuplicates() {
|
||||
Integer[] array2 = { 3, 5, 2, 14, 4 };
|
||||
Integer[] output = ArrayOperations.removeDuplicateWithOrderObjectArray(defaultObjectArray);
|
||||
|
||||
assertThat(output).containsOnlyOnce(5)
|
||||
.hasSize(5)
|
||||
.containsExactly(array2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRemoveDuplicatePreservingOrderIntArray_thenReturnArrayWithNoDuplicates() {
|
||||
int[] array2 = { 3, 5, 2, 14, 4 };
|
||||
int[] output = ArrayOperations.removeDuplicateWithOrderIntArray(defaultIntArray);
|
||||
|
||||
assertThat(output).containsOnlyOnce(5)
|
||||
.hasSize(5)
|
||||
.containsExactly(array2);
|
||||
}
|
||||
|
||||
// Print
|
||||
@Test
|
||||
public void whenPrintObjectArray_thenReturnString() {
|
||||
String output = ArrayOperations.printObjectArray(defaultObjectArray);
|
||||
String jaggedOutput = ArrayOperations.printObjectArray(defaultJaggedObjectArray);
|
||||
// Comparing to Arrays output:
|
||||
String wrongArraysOutput = Arrays.toString(defaultJaggedObjectArray);
|
||||
String differentFormatArraysOutput = Arrays.toString(defaultObjectArray);
|
||||
// We should use Arrays.deepToString for jagged arrays
|
||||
String differentFormatJaggedArraysOutput = Arrays.deepToString(defaultJaggedObjectArray);
|
||||
|
||||
assertThat(output).isEqualTo("{3,5,2,5,14,4}");
|
||||
assertThat(jaggedOutput).isEqualTo("{{1,3},{5},{}}");
|
||||
assertThat(differentFormatArraysOutput).isEqualTo("[3, 5, 2, 5, 14, 4]");
|
||||
assertThat(wrongArraysOutput).contains("[[Ljava.lang.Integer;@");
|
||||
assertThat(differentFormatJaggedArraysOutput).contains("[[1, 3], [5], []]");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPrintIntArray_thenReturnString() {
|
||||
String output = ArrayOperations.printIntArray(defaultIntArray);
|
||||
String jaggedOutput = ArrayOperations.printIntArray(defaultJaggedIntArray);
|
||||
// Comparing to Arrays output:
|
||||
String wrongArraysOutput = Arrays.toString(defaultJaggedObjectArray);
|
||||
String differentFormatArraysOutput = Arrays.toString(defaultObjectArray);
|
||||
|
||||
assertThat(output).isEqualTo("{3,5,2,5,14,4}");
|
||||
assertThat(jaggedOutput).isEqualTo("{{1,3},{5},{}}");
|
||||
assertThat(differentFormatArraysOutput).isEqualTo("[3, 5, 2, 5, 14, 4]");
|
||||
assertThat(wrongArraysOutput).contains("[[Ljava.lang.Integer;@");
|
||||
}
|
||||
|
||||
// Box and unbox
|
||||
@Test
|
||||
public void whenUnboxObjectArray_thenReturnPrimitiveArray() {
|
||||
int[] output = ArrayOperations.unboxIntegerArray(defaultObjectArray);
|
||||
|
||||
assertThat(output).containsExactly(defaultIntArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void henBoxPrimitiveArray_thenReturnObjectArray() {
|
||||
Integer[] output = ArrayOperations.boxIntArray(defaultIntArray);
|
||||
|
||||
assertThat(output).containsExactly(defaultObjectArray);
|
||||
}
|
||||
|
||||
// Map values
|
||||
@Test
|
||||
public void whenMapMultiplyingObjectArray_thenReturnMultipliedArray() {
|
||||
Integer[] multipliedExpectedArray = new Integer[] { 6, 10, 4, 10, 28, 8 };
|
||||
Integer[] output = ArrayOperations.mapObjectArray(defaultObjectArray, value -> value * 2, Integer.class);
|
||||
|
||||
assertThat(output).containsExactly(multipliedExpectedArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMapDividingObjectArray_thenReturnDividedArray() {
|
||||
Double[] multipliedExpectedArray = new Double[] { 1.5, 2.5, 1.0, 2.5, 7.0, 2.0 };
|
||||
Double[] output = ArrayOperations.mapObjectArray(defaultObjectArray, value -> value / 2.0, Double.class);
|
||||
|
||||
assertThat(output).containsExactly(multipliedExpectedArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMapIntArrayToString_thenReturnArray() {
|
||||
String[] expectedArray = new String[] { "Value: 3", "Value: 5", "Value: 2", "Value: 5", "Value: 14",
|
||||
"Value: 4" };
|
||||
String[] output = ArrayOperations.mapIntArrayToString(defaultIntArray);
|
||||
|
||||
assertThat(output).containsExactly(expectedArray);
|
||||
}
|
||||
|
||||
// Filter values
|
||||
@Test
|
||||
public void whenFilterObjectArray_thenReturnFilteredArray() {
|
||||
Integer[] multipliedExpectedArray = new Integer[] { 2, 14, 4 };
|
||||
Integer[] output = ArrayOperations.filterObjectArray(defaultObjectArray, value -> value % 2 == 0);
|
||||
|
||||
assertThat(output).containsExactly(multipliedExpectedArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFilterIntArray_thenReturnFilteredArray() {
|
||||
int[] expectedArray = new int[] { 2, 14, 4 };
|
||||
int[] output = ArrayOperations.filterIntArray(defaultIntArray, value -> (int) value % 2 == 0);
|
||||
|
||||
assertThat(output).containsExactly(expectedArray);
|
||||
}
|
||||
|
||||
// Insert between
|
||||
@Test
|
||||
public void whenInsertBetweenIntArrayToString_thenReturnNewArray() {
|
||||
int[] expectedArray = { 3, 5, 77, 88, 2, 5, 14, 4 };
|
||||
int[] output = ArrayOperations.insertBetweenIntArray(defaultIntArray, 77, 88);
|
||||
|
||||
assertThat(output).containsExactly(expectedArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenInsertBetweenObjectArrayToString_thenReturnNewArray() {
|
||||
Integer[] expectedArray = { 3, 5, 77, 99, 2, 5, 14, 4 };
|
||||
Integer[] output = ArrayOperations.insertBetweenObjectArray(defaultObjectArray, 77, 99);
|
||||
|
||||
assertThat(output).containsExactly(expectedArray);
|
||||
}
|
||||
|
||||
// Shuffle between
|
||||
@Test
|
||||
public void whenShufflingIntArraySeveralTimes_thenAtLeastOneWithDifferentOrder() {
|
||||
int[] output = ArrayOperations.shuffleIntArray(defaultIntArray);
|
||||
int[] output2 = ArrayOperations.shuffleIntArray(defaultIntArray);
|
||||
int[] output3 = ArrayOperations.shuffleIntArray(defaultIntArray);
|
||||
int[] output4 = ArrayOperations.shuffleIntArray(defaultIntArray);
|
||||
int[] output5 = ArrayOperations.shuffleIntArray(defaultIntArray);
|
||||
int[] output6 = ArrayOperations.shuffleIntArray(defaultIntArray);
|
||||
|
||||
Condition<int[]> atLeastOneArraysIsNotEqual = new Condition<int[]>(
|
||||
"at least one output should be different (order-wise)") {
|
||||
@Override
|
||||
public boolean matches(int[] value) {
|
||||
return !Arrays.equals(value, output) || !Arrays.equals(value, output2) || !Arrays.equals(value, output3)
|
||||
|| !Arrays.equals(value, output4) || !Arrays.equals(value, output5)
|
||||
|| !Arrays.equals(value, output6);
|
||||
}
|
||||
};
|
||||
|
||||
assertThat(defaultIntArray).has(atLeastOneArraysIsNotEqual);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenShufflingObjectArraySeveralTimes_thenAtLeastOneWithDifferentOrder() {
|
||||
Integer[] output = ArrayOperations.shuffleObjectArray(defaultObjectArray);
|
||||
Integer[] output2 = ArrayOperations.shuffleObjectArray(defaultObjectArray);
|
||||
Integer[] output3 = ArrayOperations.shuffleObjectArray(defaultObjectArray);
|
||||
Integer[] output4 = ArrayOperations.shuffleObjectArray(defaultObjectArray);
|
||||
Integer[] output5 = ArrayOperations.shuffleObjectArray(defaultObjectArray);
|
||||
Integer[] output6 = ArrayOperations.shuffleObjectArray(defaultObjectArray);
|
||||
|
||||
Condition<Integer[]> atLeastOneArraysIsNotEqual = new Condition<Integer[]>(
|
||||
"at least one output should be different (order-wise)") {
|
||||
@Override
|
||||
public boolean matches(Integer[] value) {
|
||||
return !Arrays.equals(value, output) || !Arrays.equals(value, output2) || !Arrays.equals(value, output3)
|
||||
|| !Arrays.equals(value, output4) || !Arrays.equals(value, output5)
|
||||
|| !Arrays.equals(value, output6);
|
||||
}
|
||||
};
|
||||
|
||||
assertThat(defaultObjectArray).has(atLeastOneArraysIsNotEqual);
|
||||
}
|
||||
|
||||
// Get random item
|
||||
@Test
|
||||
public void whenGetRandomFromIntArrayToString_thenReturnItemContainedInArray() {
|
||||
int output = ArrayOperations.getRandomFromIntArray(defaultIntArray);
|
||||
|
||||
assertThat(defaultIntArray).contains(output);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetRandomFromObjectArrayToString_thenReturnItemContainedInArray() {
|
||||
Integer output = ArrayOperations.getRandomFromObjectArray(defaultObjectArray);
|
||||
|
||||
assertThat(defaultObjectArray).contains(output);
|
||||
}
|
||||
}
|
|
@ -39,3 +39,14 @@
|
|||
- [Operating on and Removing an Item from Stream](https://www.baeldung.com/java-use-remove-item-stream)
|
||||
- [An Introduction to Synchronized Java Collections](https://www.baeldung.com/java-synchronized-collections)
|
||||
- [Guide to EnumSet](https://www.baeldung.com/java-enumset)
|
||||
- [Removing Elements from Java Collections](https://www.baeldung.com/java-collection-remove-elements)
|
||||
- [Converting a Collection to ArrayList in Java](https://www.baeldung.com/java-convert-collection-arraylist)
|
||||
- [Java 8 Streams: Find Items From One List Based On Values From Another List](https://www.baeldung.com/java-streams-find-list-items)
|
||||
- [Combining Different Types of Collections in Java](https://www.baeldung.com/java-combine-collections)
|
||||
- [Sorting in Java](http://www.baeldung.com/java-sorting)
|
||||
- [A Guide to the Java LinkedList](http://www.baeldung.com/java-linkedlist)
|
||||
- [Java List UnsupportedOperationException](http://www.baeldung.com/java-list-unsupported-operation-exception)
|
||||
- [Join and Split Arrays and Collections in Java](http://www.baeldung.com/java-join-and-split)
|
||||
- [Check If Two Lists are Equal in Java](http://www.baeldung.com/java-test-a-list-for-ordinality-and-equality)
|
||||
- [Java List Initialization in One Line](https://www.baeldung.com/java-init-list-one-line)
|
||||
- [ClassCastException: Arrays$ArrayList cannot be cast to ArrayList](https://www.baeldung.com/java-classcastexception-arrays-arraylist)
|
||||
|
|
|
@ -56,16 +56,23 @@
|
|||
<artifactId>commons-exec</artifactId>
|
||||
<version>1.3</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<openjdk.jmh.version>1.19</openjdk.jmh.version>
|
||||
<junit.platform.version>1.2.0</junit.platform.version>
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
<commons-lang3.version>3.8.1</commons-lang3.version>
|
||||
<commons-collections4.version>4.1</commons-collections4.version>
|
||||
<collections-generic.version>4.01</collections-generic.version>
|
||||
<avaitility.version>1.7.0</avaitility.version>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<assertj.version>3.11.1</assertj.version>
|
||||
<eclipse.collections.version>7.1.0</eclipse.collections.version>
|
||||
<lombok.version>1.16.12</lombok.version>
|
||||
</properties>
|
||||
</project>
|
||||
|
|
|
@ -0,0 +1,13 @@
|
|||
package com.baeldung.enummap;
|
||||
|
||||
/**
|
||||
* This enum is used for benchmarking, therefore has many values.
|
||||
*/
|
||||
public enum DummyEnum {
|
||||
CCC_000,
|
||||
CCC_001,CCC_002,CCC_003,CCC_004,CCC_005,CCC_006,CCC_007,CCC_008,CCC_009,CCC_010,
|
||||
CCC_011,CCC_012,CCC_013,CCC_014,CCC_015,CCC_016,CCC_017,CCC_018,CCC_019,CCC_020,
|
||||
CCC_021,CCC_022,CCC_023,CCC_024,CCC_025,CCC_026,CCC_027,CCC_028,CCC_029,CCC_030,
|
||||
CCC_031,CCC_032,CCC_033,CCC_034,CCC_035,CCC_036,CCC_037,CCC_038,CCC_039,CCC_040,
|
||||
CCC_041,CCC_042,CCC_043,CCC_044,CCC_045,CCC_046,CCC_047,CCC_048,CCC_049,
|
||||
}
|
|
@ -0,0 +1,119 @@
|
|||
package com.baeldung.enummap;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
import org.openjdk.jmh.runner.Runner;
|
||||
import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@BenchmarkMode({ Mode.AverageTime })
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
@Warmup(iterations = 5)
|
||||
@Measurement(iterations = 5)
|
||||
public class EnumMapBenchmarkLiveTest {
|
||||
|
||||
@State(Scope.Thread)
|
||||
public static class BenchmarkState {
|
||||
EnumMap<DummyEnum, String> enumMap = new EnumMap<>(DummyEnum.class);
|
||||
HashMap<DummyEnum, String> hashMap = new HashMap<>();
|
||||
TreeMap<DummyEnum, String> treeMap = new TreeMap<>();
|
||||
int len = DummyEnum.values().length;
|
||||
Random random = new Random();
|
||||
int randomIndex;
|
||||
|
||||
@Setup(Level.Trial)
|
||||
public void setUp() {
|
||||
DummyEnum[] values = DummyEnum.values();
|
||||
for (int i = 0; i < len; i++) {
|
||||
enumMap.put(values[i], values[i].toString());
|
||||
hashMap.put(values[i], values[i].toString());
|
||||
treeMap.put(values[i], values[i].toString());
|
||||
}
|
||||
}
|
||||
|
||||
@Setup(Level.Invocation)
|
||||
public void additionalSetup() {
|
||||
randomIndex = random.nextInt(len);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public int benchmark01_EnumMapPut(BenchmarkState s) {
|
||||
s.enumMap.put(DummyEnum.values()[s.randomIndex], DummyEnum.values()[s.randomIndex].toString());
|
||||
return ++s.randomIndex;
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public int benchmark01_HashMapPut(BenchmarkState s) {
|
||||
s.hashMap.put(DummyEnum.values()[s.randomIndex], DummyEnum.values()[s.randomIndex].toString());
|
||||
return ++s.randomIndex;
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public int benchmark01_TreeMapPut(BenchmarkState s) {
|
||||
s.treeMap.put(DummyEnum.values()[s.randomIndex], DummyEnum.values()[s.randomIndex].toString());
|
||||
return ++s.randomIndex;
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public int benchmark02_EnumMapGet(BenchmarkState s) {
|
||||
s.enumMap.get(DummyEnum.values()[s.randomIndex]);
|
||||
return ++s.randomIndex;
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public int benchmark02_HashMapGet(BenchmarkState s) {
|
||||
s.hashMap.get(DummyEnum.values()[s.randomIndex]);
|
||||
return ++s.randomIndex;
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public int benchmark02_TreeMapGet(BenchmarkState s) {
|
||||
s.treeMap.get(DummyEnum.values()[s.randomIndex]);
|
||||
return ++s.randomIndex;
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public int benchmark03_EnumMapContainsKey(BenchmarkState s) {
|
||||
s.enumMap.containsKey(DummyEnum.values()[s.randomIndex]);
|
||||
return ++s.randomIndex;
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public int benchmark03_HashMapContainsKey(BenchmarkState s) {
|
||||
s.hashMap.containsKey(DummyEnum.values()[s.randomIndex]);
|
||||
return ++s.randomIndex;
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public int benchmark03_TreeMapContainsKey(BenchmarkState s) {
|
||||
s.treeMap.containsKey(DummyEnum.values()[s.randomIndex]);
|
||||
return ++s.randomIndex;
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public int benchmark04_EnumMapContainsValue(BenchmarkState s) {
|
||||
s.enumMap.containsValue(DummyEnum.values()[s.randomIndex].toString());
|
||||
return ++s.randomIndex;
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public int benchmark04_HashMapContainsValue(BenchmarkState s) {
|
||||
s.hashMap.containsValue(DummyEnum.values()[s.randomIndex].toString());
|
||||
return ++s.randomIndex;
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public int benchmark04_TreeMapContainsValue(BenchmarkState s) {
|
||||
s.treeMap.containsValue(DummyEnum.values()[s.randomIndex].toString());
|
||||
return ++s.randomIndex;
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Options options = new OptionsBuilder().include(EnumMapBenchmarkLiveTest.class.getSimpleName()).threads(1).forks(0).shouldFailOnError(true).shouldDoGC(false).jvmArgs("-server").build();
|
||||
new Runner(options).run();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,144 @@
|
|||
package com.baeldung.enummap;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static java.util.AbstractMap.SimpleEntry;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||
|
||||
public class EnumMapUnitTest {
|
||||
public enum DayOfWeek {
|
||||
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenContructedWithEnumType_ThenOnlyAcceptThatAsKey() {
|
||||
Map dayMap = new EnumMap<>(DayOfWeek.class);
|
||||
assertThatCode(
|
||||
() -> dayMap.put(TimeUnit.NANOSECONDS, "NANOSECONDS"))
|
||||
.isInstanceOf(ClassCastException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConstructedWithEnumMap_ThenSameKeyTypeAndInitialMappings() {
|
||||
EnumMap<DayOfWeek, String> activityMap = new EnumMap<>(DayOfWeek.class);
|
||||
activityMap.put(DayOfWeek.MONDAY, "Soccer");
|
||||
activityMap.put(DayOfWeek.TUESDAY, "Basketball");
|
||||
|
||||
EnumMap<DayOfWeek, String> activityMapCopy = new EnumMap<>(activityMap);
|
||||
assertThat(activityMapCopy.size()).isEqualTo(2);
|
||||
assertThat(activityMapCopy.get(DayOfWeek.MONDAY))
|
||||
.isEqualTo("Soccer");
|
||||
assertThat(activityMapCopy.get(DayOfWeek.TUESDAY))
|
||||
.isEqualTo("Basketball");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyMap_whenConstructedWithMap_ThenException() {
|
||||
HashMap ordinaryMap = new HashMap();
|
||||
assertThatCode(() -> new EnumMap(ordinaryMap))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessage("Specified map is empty");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMapWithEntries_whenConstructedWithMap_ThenSucceed() {
|
||||
HashMap<DayOfWeek, String> ordinaryMap = new HashMap<>();
|
||||
ordinaryMap.put(DayOfWeek.MONDAY, "Soccer");
|
||||
ordinaryMap.put(DayOfWeek.TUESDAY, "Basketball");
|
||||
EnumMap<DayOfWeek, String> enumMap = new EnumMap<>(ordinaryMap);
|
||||
assertThat(enumMap.size()).isEqualTo(2);
|
||||
assertThat(enumMap.get(DayOfWeek.MONDAY)).isEqualTo("Soccer");
|
||||
assertThat(enumMap.get(DayOfWeek.TUESDAY)).isEqualTo("Basketball");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMapWithMultiTypeEntries_whenConstructedWithMap_ThenException() {
|
||||
HashMap<Enum, String> ordinaryMap = new HashMap<>();
|
||||
ordinaryMap.put(DayOfWeek.MONDAY, "Soccer");
|
||||
ordinaryMap.put(TimeUnit.MILLISECONDS, "Other enum type");
|
||||
assertThatCode(() -> new EnumMap(ordinaryMap))
|
||||
.isInstanceOf(ClassCastException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPut_thenGet() {
|
||||
Map<DayOfWeek, String> activityMap = new EnumMap(DayOfWeek.class);
|
||||
activityMap.put(DayOfWeek.WEDNESDAY, "Hiking");
|
||||
activityMap.put(DayOfWeek.THURSDAY, null);
|
||||
assertThat(activityMap.get(DayOfWeek.WEDNESDAY)).isEqualTo("Hiking");
|
||||
assertThat(activityMap.get(DayOfWeek.THURSDAY)).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMapping_whenContains_thenTrue() {
|
||||
EnumMap<DayOfWeek, String> activityMap = new EnumMap(DayOfWeek.class);
|
||||
assertThat(activityMap.containsKey(DayOfWeek.WEDNESDAY)).isFalse();
|
||||
assertThat(activityMap.containsValue("Hiking")).isFalse();
|
||||
activityMap.put(DayOfWeek.WEDNESDAY, "Hiking");
|
||||
assertThat(activityMap.containsKey(DayOfWeek.WEDNESDAY)).isTrue();
|
||||
assertThat(activityMap.containsValue("Hiking")).isTrue();
|
||||
|
||||
assertThat(activityMap.containsKey(DayOfWeek.SATURDAY)).isFalse();
|
||||
assertThat(activityMap.containsValue(null)).isFalse();
|
||||
activityMap.put(DayOfWeek.SATURDAY, null);
|
||||
assertThat(activityMap.containsKey(DayOfWeek.SATURDAY)).isTrue();
|
||||
assertThat(activityMap.containsValue(null)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRemove_thenRemoved() {
|
||||
EnumMap<DayOfWeek, String> activityMap = new EnumMap(DayOfWeek.class);
|
||||
|
||||
activityMap.put(DayOfWeek.MONDAY, "Soccer");
|
||||
assertThat(activityMap.remove(DayOfWeek.MONDAY)).isEqualTo("Soccer");
|
||||
assertThat(activityMap.containsKey(DayOfWeek.MONDAY)).isFalse();
|
||||
|
||||
activityMap.put(DayOfWeek.MONDAY, "Soccer");
|
||||
assertThat(activityMap.remove(DayOfWeek.MONDAY, "Hiking")).isEqualTo(false);
|
||||
assertThat(activityMap.remove(DayOfWeek.MONDAY, "Soccer")).isEqualTo(true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSubView_thenSubViewOrdered() {
|
||||
EnumMap<DayOfWeek, String> activityMap = new EnumMap(DayOfWeek.class);
|
||||
activityMap.put(DayOfWeek.THURSDAY, "Karate");
|
||||
activityMap.put(DayOfWeek.WEDNESDAY, "Hiking");
|
||||
activityMap.put(DayOfWeek.MONDAY, "Soccer");
|
||||
|
||||
Collection<String> values = activityMap.values();
|
||||
assertThat(values).containsExactly("Soccer", "Hiking", "Karate");
|
||||
|
||||
Set<DayOfWeek> keys = activityMap.keySet();
|
||||
assertThat(keys)
|
||||
.containsExactly(DayOfWeek.MONDAY, DayOfWeek.WEDNESDAY,DayOfWeek.THURSDAY);
|
||||
|
||||
assertThat(activityMap.entrySet())
|
||||
.containsExactly(
|
||||
new SimpleEntry(DayOfWeek.MONDAY, "Soccer"),
|
||||
new SimpleEntry(DayOfWeek.WEDNESDAY, "Hiking"),
|
||||
new SimpleEntry(DayOfWeek.THURSDAY, "Karate"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSubView_whenChange_thenReflected() {
|
||||
EnumMap<DayOfWeek, String> activityMap = new EnumMap(DayOfWeek.class);
|
||||
activityMap.put(DayOfWeek.THURSDAY, "Karate");
|
||||
activityMap.put(DayOfWeek.WEDNESDAY, "Hiking");
|
||||
activityMap.put(DayOfWeek.MONDAY, "Soccer");
|
||||
|
||||
Collection<String> values = activityMap.values();
|
||||
assertThat(values).containsExactly("Soccer", "Hiking", "Karate");
|
||||
|
||||
activityMap.put(DayOfWeek.TUESDAY, "Basketball");
|
||||
assertThat(values)
|
||||
.containsExactly("Soccer", "Basketball", "Hiking", "Karate");
|
||||
|
||||
values.remove("Hiking");
|
||||
assertThat(activityMap.containsKey(DayOfWeek.WEDNESDAY)).isFalse();
|
||||
assertThat(activityMap.size()).isEqualTo(3);
|
||||
}
|
||||
}
|
|
@ -30,3 +30,4 @@
|
|||
- [Life Cycle of a Thread in Java](http://www.baeldung.com/java-thread-lifecycle)
|
||||
- [Runnable vs. Callable in Java](http://www.baeldung.com/java-runnable-callable)
|
||||
- [Brief Introduction to Java Thread.yield()](https://www.baeldung.com/java-thread-yield)
|
||||
- [Print Even and Odd Numbers Using 2 Threads](https://www.baeldung.com/java-even-odd-numbers-with-2-threads)
|
||||
|
|
|
@ -0,0 +1,75 @@
|
|||
package com.baeldung.concurrent.evenandodd;
|
||||
|
||||
import java.util.concurrent.Semaphore;
|
||||
|
||||
public class PrintEvenOddSemaphore {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SharedPrinter sp = new SharedPrinter();
|
||||
Thread odd = new Thread(new Odd(sp, 10), "Odd");
|
||||
Thread even = new Thread(new Even(sp, 10), "Even");
|
||||
|
||||
odd.start();
|
||||
even.start();
|
||||
}
|
||||
}
|
||||
|
||||
class SharedPrinter {
|
||||
|
||||
private final Semaphore semEven = new Semaphore(0);
|
||||
private final Semaphore semOdd = new Semaphore(1);
|
||||
|
||||
void printEvenNum(int num) {
|
||||
try {
|
||||
semEven.acquire();
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
System.out.println(Thread.currentThread().getName() + ":"+num);
|
||||
semOdd.release();
|
||||
}
|
||||
|
||||
void printOddNum(int num) {
|
||||
try {
|
||||
semOdd.acquire();
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
System.out.println(Thread.currentThread().getName() + ":"+ num);
|
||||
semEven.release();
|
||||
}
|
||||
}
|
||||
|
||||
class Even implements Runnable {
|
||||
private final SharedPrinter sp;
|
||||
private final int max;
|
||||
|
||||
Even(SharedPrinter sp, int max) {
|
||||
this.sp = sp;
|
||||
this.max = max;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
for (int i = 2; i <= max; i = i + 2) {
|
||||
sp.printEvenNum(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class Odd implements Runnable {
|
||||
private SharedPrinter sp;
|
||||
private int max;
|
||||
|
||||
Odd(SharedPrinter sp, int max) {
|
||||
this.sp = sp;
|
||||
this.max = max;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
for (int i = 1; i <= max; i = i + 2) {
|
||||
sp.printOddNum(i);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,68 @@
|
|||
package com.baeldung.concurrent.evenandodd;
|
||||
|
||||
public class PrintEvenOddWaitNotify {
|
||||
|
||||
public static void main(String... args) {
|
||||
Printer print = new Printer();
|
||||
Thread t1 = new Thread(new TaskEvenOdd(print, 10, false), "Odd");
|
||||
Thread t2 = new Thread(new TaskEvenOdd(print, 10, true), "Even");
|
||||
t1.start();
|
||||
t2.start();
|
||||
}
|
||||
}
|
||||
|
||||
class TaskEvenOdd implements Runnable {
|
||||
private final int max;
|
||||
private final Printer print;
|
||||
private final boolean isEvenNumber;
|
||||
|
||||
TaskEvenOdd(Printer print, int max, boolean isEvenNumber) {
|
||||
this.print = print;
|
||||
this.max = max;
|
||||
this.isEvenNumber = isEvenNumber;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
int number = isEvenNumber ? 2 : 1;
|
||||
while (number <= max) {
|
||||
if (isEvenNumber) {
|
||||
print.printEven(number);
|
||||
} else {
|
||||
print.printOdd(number);
|
||||
}
|
||||
number += 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class Printer {
|
||||
private volatile boolean isOdd;
|
||||
|
||||
synchronized void printEven(int number) {
|
||||
while (!isOdd) {
|
||||
try {
|
||||
wait();
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
System.out.println(Thread.currentThread().getName() + ":" + number);
|
||||
isOdd = false;
|
||||
notify();
|
||||
}
|
||||
|
||||
synchronized void printOdd(int number) {
|
||||
while (isOdd) {
|
||||
try {
|
||||
wait();
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
System.out.println(Thread.currentThread().getName() + ":" + number);
|
||||
isOdd = true;
|
||||
notify();
|
||||
}
|
||||
|
||||
}
|
|
@ -33,3 +33,4 @@
|
|||
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
|
||||
- [Read a File into an ArrayList](https://www.baeldung.com/java-file-to-arraylist)
|
||||
- [Guide to Java OutputStream](https://www.baeldung.com/java-outputstream)
|
||||
- [Reading a CSV File into an Array](https://www.baeldung.com/java-csv-file-array)
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue