Merge remote-tracking branch 'upstream/master'
This commit is contained in:
commit
b3e70acc05
|
@ -4,4 +4,3 @@
|
|||
- [Implementing Simple State Machines with Java Enums](https://www.baeldung.com/java-enum-simple-state-machine)
|
||||
- [Converting Between Roman and Arabic Numerals in Java](http://www.baeldung.com/java-convert-roman-arabic)
|
||||
- [Practical Java Examples of the Big O Notation](http://www.baeldung.com/java-algorithm-complexity)
|
||||
- [An Introduction to the Theory of Big-O Notation](http://www.baeldung.com/big-o-notation)
|
|
@ -0,0 +1,5 @@
|
|||
Dear <% out << (user) %>,
|
||||
Please read the requested article below.
|
||||
<% out << (articleText) %>
|
||||
From,
|
||||
<% out << (signature) %>
|
|
@ -0,0 +1,3 @@
|
|||
Dear $user,
|
||||
Thanks for subscribing our services.
|
||||
${signature}
|
|
@ -0,0 +1,96 @@
|
|||
package com.baeldung.templateengine
|
||||
|
||||
import groovy.text.SimpleTemplateEngine
|
||||
import groovy.text.StreamingTemplateEngine
|
||||
import groovy.text.GStringTemplateEngine
|
||||
import groovy.text.XmlTemplateEngine
|
||||
import groovy.text.XmlTemplateEngine
|
||||
import groovy.text.markup.MarkupTemplateEngine
|
||||
import groovy.text.markup.TemplateConfiguration
|
||||
|
||||
class TemplateEnginesUnitTest extends GroovyTestCase {
|
||||
|
||||
def bindMap = [user: "Norman", signature: "Baeldung"]
|
||||
|
||||
void testSimpleTemplateEngine() {
|
||||
def smsTemplate = 'Dear <% print user %>, Thanks for reading our Article. ${signature}'
|
||||
def smsText = new SimpleTemplateEngine().createTemplate(smsTemplate).make(bindMap)
|
||||
|
||||
assert smsText.toString() == "Dear Norman, Thanks for reading our Article. Baeldung"
|
||||
}
|
||||
|
||||
void testStreamingTemplateEngine() {
|
||||
def articleEmailTemplate = new File('src/main/resources/articleEmail.template')
|
||||
bindMap.articleText = """1. Overview
|
||||
This is a tutorial article on Template Engines""" //can be a string larger than 64k
|
||||
|
||||
def articleEmailText = new StreamingTemplateEngine().createTemplate(articleEmailTemplate).make(bindMap)
|
||||
|
||||
assert articleEmailText.toString() == """Dear Norman,
|
||||
Please read the requested article below.
|
||||
1. Overview
|
||||
This is a tutorial article on Template Engines
|
||||
From,
|
||||
Baeldung"""
|
||||
|
||||
}
|
||||
|
||||
void testGStringTemplateEngine() {
|
||||
def emailTemplate = new File('src/main/resources/email.template')
|
||||
def emailText = new GStringTemplateEngine().createTemplate(emailTemplate).make(bindMap)
|
||||
|
||||
assert emailText.toString() == "Dear Norman,\nThanks for subscribing our services.\nBaeldung"
|
||||
}
|
||||
|
||||
void testXmlTemplateEngine() {
|
||||
def emailXmlTemplate = '''<xs xmlns:gsp='groovy-server-pages'>
|
||||
<gsp:scriptlet>def emailContent = "Thanks for subscribing our services."</gsp:scriptlet>
|
||||
<email>
|
||||
<greet>Dear ${user}</greet>
|
||||
<content><gsp:expression>emailContent</gsp:expression></content>
|
||||
<signature>${signature}</signature>
|
||||
</email>
|
||||
</xs>'''
|
||||
def emailXml = new XmlTemplateEngine().createTemplate(emailXmlTemplate).make(bindMap)
|
||||
println emailXml.toString()
|
||||
}
|
||||
|
||||
void testMarkupTemplateEngineHtml() {
|
||||
def emailHtmlTemplate = """html {
|
||||
head {
|
||||
title('Service Subscription Email')
|
||||
}
|
||||
body {
|
||||
p('Dear Norman')
|
||||
p('Thanks for subscribing our services.')
|
||||
p('Baeldung')
|
||||
}
|
||||
}"""
|
||||
|
||||
|
||||
def emailHtml = new MarkupTemplateEngine().createTemplate(emailHtmlTemplate).make()
|
||||
println emailHtml.toString()
|
||||
|
||||
}
|
||||
|
||||
void testMarkupTemplateEngineXml() {
|
||||
def emailXmlTemplate = """xmlDeclaration()
|
||||
xs{
|
||||
email {
|
||||
greet('Dear Norman')
|
||||
content('Thanks for subscribing our services.')
|
||||
signature('Baeldung')
|
||||
}
|
||||
}
|
||||
"""
|
||||
TemplateConfiguration config = new TemplateConfiguration()
|
||||
config.autoIndent = true
|
||||
config.autoEscape = true
|
||||
config.autoNewLine = true
|
||||
|
||||
def emailXml = new MarkupTemplateEngine(config).createTemplate(emailXmlTemplate).make()
|
||||
|
||||
println emailXml.toString()
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
## Relevant Articles
|
||||
|
||||
- [Extending an Array’s Length](https://www.baeldung.com/java-array-add-element-at-the-end)
|
|
@ -1,4 +1,6 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
<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>
|
||||
|
@ -12,7 +14,7 @@
|
|||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../</relativePath>
|
||||
<relativePath>../..</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
@ -21,6 +23,12 @@
|
|||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
@ -41,6 +49,7 @@
|
|||
<maven.compiler.source.version>11</maven.compiler.source.version>
|
||||
<maven.compiler.target.version>11</maven.compiler.target.version>
|
||||
<guava.version>27.1-jre</guava.version>
|
||||
<assertj.version>3.11.1</assertj.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -0,0 +1,19 @@
|
|||
package com.baeldung.predicate.not;
|
||||
|
||||
public class Person {
|
||||
private static final int ADULT_AGE = 18;
|
||||
|
||||
private int age;
|
||||
|
||||
public Person(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public boolean isAdult() {
|
||||
return age >= ADULT_AGE;
|
||||
}
|
||||
|
||||
public boolean isNotAdult() {
|
||||
return !isAdult();
|
||||
}
|
||||
}
|
|
@ -7,7 +7,7 @@ import junit.framework.TestSuite;
|
|||
/**
|
||||
* Unit test for simple App.
|
||||
*/
|
||||
public class AppTest
|
||||
public class AppUnitTest
|
||||
extends TestCase
|
||||
{
|
||||
/**
|
||||
|
@ -15,7 +15,7 @@ public class AppTest
|
|||
*
|
||||
* @param testName name of the test case
|
||||
*/
|
||||
public AppTest( String testName )
|
||||
public AppUnitTest(String testName )
|
||||
{
|
||||
super( testName );
|
||||
}
|
||||
|
@ -25,7 +25,7 @@ public class AppTest
|
|||
*/
|
||||
public static Test suite()
|
||||
{
|
||||
return new TestSuite( AppTest.class );
|
||||
return new TestSuite( AppUnitTest.class );
|
||||
}
|
||||
|
||||
/**
|
|
@ -32,7 +32,7 @@ import java.util.stream.Collectors;
|
|||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class HttpClientTest {
|
||||
public class HttpClientUnitTest {
|
||||
|
||||
@Test
|
||||
public void shouldReturnSampleDataContentWhenConnectViaSystemProxy() throws IOException, InterruptedException, URISyntaxException {
|
|
@ -19,7 +19,7 @@ import java.time.Duration;
|
|||
|
||||
import org.junit.Test;
|
||||
|
||||
public class HttpRequestTest {
|
||||
public class HttpRequestUnitTest {
|
||||
|
||||
@Test
|
||||
public void shouldReturnStatusOKWhenSendGetRequest() throws IOException, InterruptedException, URISyntaxException {
|
|
@ -14,7 +14,7 @@ import java.net.http.HttpResponse;
|
|||
|
||||
import org.junit.Test;
|
||||
|
||||
public class HttpResponseTest {
|
||||
public class HttpResponseUnitTest {
|
||||
|
||||
@Test
|
||||
public void shouldReturnStatusOKWhenSendGetRequest() throws IOException, InterruptedException, URISyntaxException {
|
|
@ -0,0 +1,61 @@
|
|||
package com.baeldung.predicate.not;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static java.util.function.Predicate.not;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class PersonUnitTest {
|
||||
private List<Person> people;
|
||||
|
||||
@BeforeEach
|
||||
void preparePeople() {
|
||||
people = Arrays.asList(
|
||||
new Person(1),
|
||||
new Person(18),
|
||||
new Person(2)
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPeople_whenFilterIsAdult_thenOneResult() {
|
||||
List<Person> adults = people.stream()
|
||||
.filter(Person::isAdult)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(adults).size().isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPeople_whenFilterIsAdultNegated_thenTwoResults() {
|
||||
List<Person> nonAdults = people.stream()
|
||||
.filter(person -> !person.isAdult())
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(nonAdults).size().isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPeople_whenFilterIsNotAdult_thenTwoResults() {
|
||||
List<Person> nonAdults = people.stream()
|
||||
.filter(Person::isNotAdult)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(nonAdults).size().isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenPeople_whenFilterNotIsAdult_thenTwoResults() {
|
||||
List<Person> nonAdults = people.stream()
|
||||
.filter(not(Person::isAdult))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(nonAdults).size().isEqualTo(2);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
package com.baeldung.string;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class StringAPITest {
|
||||
|
||||
@Test
|
||||
public void whenPositiveArgument_thenReturnIndentedString() {
|
||||
String multilineStr = "This is\na multiline\nstring.";
|
||||
String outputStr = " This is\n a multiline\n string.\n";
|
||||
|
||||
String postIndent = multilineStr.indent(3);
|
||||
|
||||
assertThat(postIndent, equalTo(outputStr));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNegativeArgument_thenReturnReducedIndentedString() {
|
||||
String multilineStr = " This is\n a multiline\n string.";
|
||||
String outputStr = " This is\n a multiline\n string.\n";
|
||||
|
||||
String postIndent = multilineStr.indent(-2);
|
||||
|
||||
assertThat(postIndent, equalTo(outputStr));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenTransformUsingLamda_thenReturnTransformedString() {
|
||||
String result = "hello".transform(input -> input + " world!");
|
||||
|
||||
assertThat(result, equalTo("hello world!"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenTransformUsingParseInt_thenReturnInt() {
|
||||
int result = "42".transform(Integer::parseInt);
|
||||
|
||||
assertThat(result, equalTo(42));
|
||||
}
|
||||
}
|
|
@ -3,4 +3,5 @@
|
|||
## Core Java 8 Cookbooks and Examples (part 2)
|
||||
|
||||
### Relevant Articles:
|
||||
- [Anonymous Classes in Java](http://www.baeldung.com/)
|
||||
- [Anonymous Classes in Java](https://www.baeldung.com/java-anonymous-classes)
|
||||
- [Run JAR Application With Command Line Arguments](https://www.baeldung.com/java-run-jar-with-arguments)
|
||||
|
|
|
@ -20,7 +20,6 @@
|
|||
- [Multi-Release Jar Files](https://www.baeldung.com/java-multi-release-jar)
|
||||
- [Ahead of Time Compilation (AoT)](https://www.baeldung.com/ahead-of-time-compilation)
|
||||
- [Java 9 Process API Improvements](https://www.baeldung.com/java-9-process-api)
|
||||
- [Guide to java.lang.Process API](https://www.baeldung.com/java-process-api)
|
||||
- [Java 9 java.util.Objects Additions](https://www.baeldung.com/java-9-objects-new)
|
||||
- [Java 9 Reactive Streams](https://www.baeldung.com/java-9-reactive-streams)
|
||||
- [Java 9 Optional API Additions](https://www.baeldung.com/java-9-optional)
|
||||
|
@ -31,4 +30,4 @@
|
|||
- [A Guide to Java 9 Modularity](https://www.baeldung.com/java-9-modularity)
|
||||
- [Java 9 Platform Module API](https://www.baeldung.com/java-9-module-api)
|
||||
- [Java 9 Platform Logging API](https://www.baeldung.com/java-9-logging-api)
|
||||
|
||||
- [Filtering a Stream of Optionals in Java](https://www.baeldung.com/java-filter-stream-of-optional)
|
||||
|
|
|
@ -0,0 +1,10 @@
|
|||
=========
|
||||
|
||||
## Core Java Collections Array List Cookbooks and Examples
|
||||
|
||||
### Relevant Articles:
|
||||
- [Immutable ArrayList in Java](http://www.baeldung.com/java-immutable-list)
|
||||
- [Guide to the Java ArrayList](http://www.baeldung.com/java-arraylist)
|
||||
- [Add Multiple Items to an Java ArrayList](http://www.baeldung.com/java-add-items-array-list)
|
||||
- [ClassCastException: Arrays$ArrayList cannot be cast to ArrayList](https://www.baeldung.com/java-classcastexception-arrays-arraylist)
|
||||
- [Multi Dimensional ArrayList in Java](https://www.baeldung.com/java-multi-dimensional-arraylist)
|
|
@ -0,0 +1,46 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-collections-array-list</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-collections-array-list</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>${commons-collections4.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<commons-collections4.version>4.1</commons-collections4.version>
|
||||
<commons-lang3.version>3.8.1</commons-lang3.version>
|
||||
<assertj.version>3.11.1</assertj.version>
|
||||
</properties>
|
||||
</project>
|
|
@ -0,0 +1,28 @@
|
|||
package com.baeldung.java.list;
|
||||
|
||||
public class Flower {
|
||||
|
||||
private String name;
|
||||
private int petals;
|
||||
|
||||
public Flower(String name, int petals) {
|
||||
this.name = name;
|
||||
this.petals = petals;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public int getPetals() {
|
||||
return petals;
|
||||
}
|
||||
|
||||
public void setPetals(int petals) {
|
||||
this.petals = petals;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
|
@ -0,0 +1,17 @@
|
|||
=========
|
||||
|
||||
## Core Java Collections List Cookbooks and Examples
|
||||
|
||||
### Relevant Articles:
|
||||
- [Check If Two Lists are Equal in Java](http://www.baeldung.com/java-test-a-list-for-ordinality-and-equality)
|
||||
- [Java 8 Streams: Find Items From One List Based On Values From Another List](https://www.baeldung.com/java-streams-find-list-items)
|
||||
- [A Guide to the Java LinkedList](http://www.baeldung.com/java-linkedlist)
|
||||
- [Java List UnsupportedOperationException](http://www.baeldung.com/java-list-unsupported-operation-exception)
|
||||
- [Java List Initialization in One Line](https://www.baeldung.com/java-init-list-one-line)
|
||||
- [Ways to Iterate Over a List in Java](https://www.baeldung.com/java-iterate-list)
|
||||
- [Flattening Nested Collections in Java](http://www.baeldung.com/java-flatten-nested-collections)
|
||||
- [Intersection of Two Lists in Java](https://www.baeldung.com/java-lists-intersection)
|
||||
- [Determine If All Elements Are the Same in a Java List](https://www.baeldung.com/java-list-all-equal)
|
||||
- [List of Primitive Integer Values in Java](https://www.baeldung.com/java-list-primitive-int)
|
||||
- [Performance Comparison of Primitive Lists in Java](https://www.baeldung.com/java-list-primitive-performance)
|
||||
- [Filtering a Java Collection by a List](https://www.baeldung.com/java-filter-collection-by-list)
|
|
@ -0,0 +1,76 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-collections-list-2</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-collections-list-2</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>${commons-collections4.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>net.sf.trove4j</groupId>
|
||||
<artifactId>trove4j</artifactId>
|
||||
<version>${trove4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>it.unimi.dsi</groupId>
|
||||
<artifactId>fastutil</artifactId>
|
||||
<version>${fastutil.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>colt</groupId>
|
||||
<artifactId>colt</artifactId>
|
||||
<version>${colt.version}</version>
|
||||
</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-core.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<commons-collections4.version>4.1</commons-collections4.version>
|
||||
<commons-lang3.version>3.8.1</commons-lang3.version>
|
||||
<assertj.version>3.11.1</assertj.version>
|
||||
<trove4j.version>3.0.2</trove4j.version>
|
||||
<fastutil.version>8.1.0</fastutil.version>
|
||||
<colt.version>1.2.0</colt.version>
|
||||
</properties>
|
||||
</project>
|
|
@ -0,0 +1,13 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
|
@ -3,31 +3,14 @@
|
|||
## Core Java Collections List Cookbooks and Examples
|
||||
|
||||
### Relevant Articles:
|
||||
- [Immutable ArrayList in Java](http://www.baeldung.com/java-immutable-list)
|
||||
- [Guide to the Java ArrayList](http://www.baeldung.com/java-arraylist)
|
||||
- [Java – Get Random Item/Element From a List](http://www.baeldung.com/java-random-list-element)
|
||||
- [Removing all nulls from a List in Java](http://www.baeldung.com/java-remove-nulls-from-list)
|
||||
- [Removing all duplicates from a List in Java](http://www.baeldung.com/java-remove-duplicates-from-list)
|
||||
- [How to TDD a List Implementation in Java](http://www.baeldung.com/java-test-driven-list)
|
||||
- [Iterating Backward Through a List](http://www.baeldung.com/java-list-iterate-backwards)
|
||||
- [Add Multiple Items to an Java ArrayList](http://www.baeldung.com/java-add-items-array-list)
|
||||
- [Remove the First Element from a List](http://www.baeldung.com/java-remove-first-element-from-list)
|
||||
- [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java)
|
||||
- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)
|
||||
- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max)
|
||||
- [Collections.emptyList() vs. New List Instance](https://www.baeldung.com/java-collections-emptylist-new-list)
|
||||
- [Remove All Occurrences of a Specific Value from a List](https://www.baeldung.com/java-remove-value-from-list)
|
||||
- [Check If Two Lists are Equal in Java](http://www.baeldung.com/java-test-a-list-for-ordinality-and-equality)
|
||||
- [Java 8 Streams: Find Items From One List Based On Values From Another List](https://www.baeldung.com/java-streams-find-list-items)
|
||||
- [A Guide to the Java LinkedList](http://www.baeldung.com/java-linkedlist)
|
||||
- [Java List UnsupportedOperationException](http://www.baeldung.com/java-list-unsupported-operation-exception)
|
||||
- [Java List Initialization in One Line](https://www.baeldung.com/java-init-list-one-line)
|
||||
- [Ways to Iterate Over a List in Java](https://www.baeldung.com/java-iterate-list)
|
||||
- [ClassCastException: Arrays$ArrayList cannot be cast to ArrayList](https://www.baeldung.com/java-classcastexception-arrays-arraylist)
|
||||
- [Flattening Nested Collections in Java](http://www.baeldung.com/java-flatten-nested-collections)
|
||||
- [Intersection of Two Lists in Java](https://www.baeldung.com/java-lists-intersection)
|
||||
- [Multi Dimensional ArrayList in Java](https://www.baeldung.com/java-multi-dimensional-arraylist)
|
||||
- [Determine If All Elements Are the Same in a Java List](https://www.baeldung.com/java-list-all-equal)
|
||||
- [List of Primitive Integer Values in Java](https://www.baeldung.com/java-list-primitive-int)
|
||||
- [Performance Comparison of Primitive Lists in Java](https://www.baeldung.com/java-list-primitive-performance)
|
||||
- [Filtering a Java Collection by a List](https://www.baeldung.com/java-filter-collection-by-list)
|
||||
|
|
|
@ -36,42 +36,12 @@
|
|||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>net.sf.trove4j</groupId>
|
||||
<artifactId>trove4j</artifactId>
|
||||
<version>${trove4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>it.unimi.dsi</groupId>
|
||||
<artifactId>fastutil</artifactId>
|
||||
<version>${fastutil.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>colt</groupId>
|
||||
<artifactId>colt</artifactId>
|
||||
<version>${colt.version}</version>
|
||||
</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-core.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<commons-collections4.version>4.1</commons-collections4.version>
|
||||
<commons-lang3.version>3.8.1</commons-lang3.version>
|
||||
<avaitility.version>1.7.0</avaitility.version>
|
||||
<assertj.version>3.11.1</assertj.version>
|
||||
<trove4j.version>3.0.2</trove4j.version>
|
||||
<fastutil.version>8.1.0</fastutil.version>
|
||||
<colt.version>1.2.0</colt.version>
|
||||
</properties>
|
||||
</project>
|
||||
|
|
|
@ -40,3 +40,4 @@
|
|||
- [How to Write to a CSV File in Java](https://www.baeldung.com/java-csv)
|
||||
- [List Files in a Directory in Java](https://www.baeldung.com/java-list-directory-files)
|
||||
- [Java InputStream to Byte Array and ByteBuffer](https://www.baeldung.com/convert-input-stream-to-array-of-bytes)
|
||||
- [Introduction to the Java NIO Selector](https://www.baeldung.com/java-nio-selector)
|
||||
|
|
|
@ -0,0 +1,30 @@
|
|||
<?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>consumermodule</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
<version>1.0</version>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.decoupling-pattern1</groupId>
|
||||
<artifactId>decoupling-pattern1</artifactId>
|
||||
<version>1.0</version>
|
||||
</parent>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.baeldung.servicemodule</groupId>
|
||||
<artifactId>servicemodule</artifactId>
|
||||
<version>1.0</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
|
@ -0,0 +1,13 @@
|
|||
package com.baeldung.consumermodule;
|
||||
|
||||
import com.baeldung.servicemodule.external.TextService;
|
||||
import com.baeldung.servicemodule.external.TextServiceFactory;
|
||||
|
||||
public class Application {
|
||||
|
||||
public static void main(String args[]) {
|
||||
TextService textService = TextServiceFactory.getTextService("lowercase");
|
||||
System.out.println(textService.processText("Hello from Baeldung!"));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
module com.baeldung.consumermodule {
|
||||
requires com.baeldung.servicemodule;
|
||||
}
|
|
@ -0,0 +1,35 @@
|
|||
<?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.decoupling-pattern1</groupId>
|
||||
<artifactId>decoupling-pattern1</artifactId>
|
||||
<version>1.0</version>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<modules>
|
||||
<module>servicemodule</module>
|
||||
<module>consumermodule</module>
|
||||
</modules>
|
||||
|
||||
<build>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.8.0</version>
|
||||
<configuration>
|
||||
<source>11</source>
|
||||
<target>11</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
</project>
|
|
@ -0,0 +1,24 @@
|
|||
<?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.servicemodule</groupId>
|
||||
<artifactId>servicemodule</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.decoupling-pattern1</groupId>
|
||||
<artifactId>decoupling-pattern1</artifactId>
|
||||
<version>1.0</version>
|
||||
</parent>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,7 @@
|
|||
package com.baeldung.servicemodule.external;
|
||||
|
||||
public interface TextService {
|
||||
|
||||
String processText(String text);
|
||||
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package com.baeldung.servicemodule.external;
|
||||
|
||||
import com.baeldung.servicemodule.internal.LowercaseTextService;
|
||||
import com.baeldung.servicemodule.internal.UppercaseTextService;
|
||||
|
||||
public class TextServiceFactory {
|
||||
|
||||
private TextServiceFactory() {}
|
||||
|
||||
public static TextService getTextService(String name) {
|
||||
return name.equalsIgnoreCase("lowercase") ? new LowercaseTextService(): new UppercaseTextService();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,12 @@
|
|||
package com.baeldung.servicemodule.internal;
|
||||
|
||||
import com.baeldung.servicemodule.external.TextService;
|
||||
|
||||
public class LowercaseTextService implements TextService {
|
||||
|
||||
@Override
|
||||
public String processText(String text) {
|
||||
return text.toLowerCase();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,12 @@
|
|||
package com.baeldung.servicemodule.internal;
|
||||
|
||||
import com.baeldung.servicemodule.external.TextService;
|
||||
|
||||
public class UppercaseTextService implements TextService {
|
||||
|
||||
@Override
|
||||
public String processText(String text) {
|
||||
return text.toUpperCase();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
module com.baeldung.servicemodule {
|
||||
exports com.baeldung.servicemodule.external;
|
||||
}
|
|
@ -0,0 +1,38 @@
|
|||
<?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">
|
||||
<parent>
|
||||
<artifactId>com.baeldung.decoupling-pattern2</artifactId>
|
||||
<groupId>decoupling-pattern2</groupId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.baeldung.consumermodule</groupId>
|
||||
<artifactId>consumermodule</artifactId>
|
||||
<version>1.0</version>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.baeldung.servicemodule</groupId>
|
||||
<artifactId>servicemodule</artifactId>
|
||||
<version>1.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.baeldung.providermodule</groupId>
|
||||
<artifactId>providermodule</artifactId>
|
||||
<version>1.0</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,15 @@
|
|||
package com.baeldung.consumermodule;
|
||||
|
||||
import com.baeldung.servicemodule.TextService;
|
||||
|
||||
import java.util.ServiceLoader;
|
||||
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
ServiceLoader<TextService> services = ServiceLoader.load(TextService.class);
|
||||
for (final TextService service: services) {
|
||||
System.out.println("The service " + service.getClass().getSimpleName() + " says: " + service.parseText("Hello from Baeldung!"));
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
module com.baeldung.consumermodule {
|
||||
requires com.baeldung.servicemodule;
|
||||
uses com.baeldung.servicemodule.TextService;
|
||||
}
|
|
@ -0,0 +1,34 @@
|
|||
<?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.decoupling-pattern2</groupId>
|
||||
<artifactId>decoupling-pattern2</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<modules>
|
||||
<module>servicemodule</module>
|
||||
<module>providermodule</module>
|
||||
<module>consumermodule</module>
|
||||
</modules>
|
||||
|
||||
<build>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.8.0</version>
|
||||
<configuration>
|
||||
<source>11</source>
|
||||
<target>11</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,34 @@
|
|||
<?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.providermodule</groupId>
|
||||
<artifactId>providermodule</artifactId>
|
||||
<version>1.0</version>
|
||||
|
||||
<parent>
|
||||
<artifactId>com.baeldung.decoupling-pattern2</artifactId>
|
||||
<groupId>decoupling-pattern2</groupId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.baeldung.servicemodule</groupId>
|
||||
<artifactId>servicemodule</artifactId>
|
||||
<version>1.0</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,10 @@
|
|||
package com.baeldung.providermodule;
|
||||
|
||||
import com.baeldung.servicemodule.TextService;
|
||||
|
||||
public class LowercaseTextService implements TextService {
|
||||
@Override
|
||||
public String parseText(String text) {
|
||||
return text.toLowerCase();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
module com.baeldung.providermodule {
|
||||
requires com.baeldung.servicemodule;
|
||||
provides com.baeldung.servicemodule.TextService with com.baeldung.providermodule.LowercaseTextService;
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
<?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>
|
||||
<parent>
|
||||
<artifactId>>com.baeldung.decoupling-pattern2</artifactId>
|
||||
<groupId>decoupling-pattern2</groupId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<groupId>com.baeldung.servicemodule</groupId>
|
||||
<artifactId>servicemodule</artifactId>
|
||||
<version>1.0</version>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,6 @@
|
|||
package com.baeldung.servicemodule;
|
||||
|
||||
public interface TextService {
|
||||
|
||||
String parseText(String text);
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
module com.baeldung.servicemodule {
|
||||
exports com.baeldung.servicemodule;
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
## Relevant Articles
|
||||
|
||||
- [Void Type in Java](https://www.baeldung.com/java-void-type)
|
|
@ -51,3 +51,4 @@
|
|||
- [Java Bitwise Operators](https://www.baeldung.com/java-bitwise-operators)
|
||||
- [Guide to Creating and Running a Jar File in Java](https://www.baeldung.com/java-create-jar)
|
||||
- [Making a JSON POST Request With HttpURLConnection](https://www.baeldung.com/httpurlconnection-post)
|
||||
- [Convert Hex to ASCII in Java](https://www.baeldung.com/java-convert-hex-to-ascii)
|
||||
|
|
|
@ -0,0 +1,3 @@
|
|||
## Relevant Articles
|
||||
|
||||
- [Java 9 Migration Issues and Resolutions](https://www.baeldung.com/java-9-migration-issue)
|
|
@ -0,0 +1,15 @@
|
|||
package com.baeldung.ddd.order.doubledispatch;
|
||||
|
||||
import org.joda.money.CurrencyUnit;
|
||||
import org.joda.money.Money;
|
||||
|
||||
public class AmountBasedDiscountPolicy implements DiscountPolicy {
|
||||
@Override
|
||||
public double discount(Order order) {
|
||||
if (order.totalCost()
|
||||
.isGreaterThan(Money.of(CurrencyUnit.USD, 500.00))) {
|
||||
return 0.10;
|
||||
} else
|
||||
return 0;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
package com.baeldung.ddd.order.doubledispatch;
|
||||
|
||||
public interface DiscountPolicy {
|
||||
double discount(Order order);
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
package com.baeldung.ddd.order.doubledispatch;
|
||||
|
||||
public class FlatDiscountPolicy implements DiscountPolicy {
|
||||
@Override
|
||||
public double discount(Order order) {
|
||||
return 0.01;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
package com.baeldung.ddd.order.doubledispatch;
|
||||
|
||||
import java.math.RoundingMode;
|
||||
import java.util.List;
|
||||
|
||||
import org.joda.money.Money;
|
||||
|
||||
import com.baeldung.ddd.order.OrderLine;
|
||||
import com.baeldung.ddd.order.doubledispatch.visitor.OrderVisitor;
|
||||
import com.baeldung.ddd.order.doubledispatch.visitor.Visitable;
|
||||
|
||||
public class Order extends com.baeldung.ddd.order.Order implements Visitable<OrderVisitor> {
|
||||
public Order(List<OrderLine> orderLines) {
|
||||
super(orderLines);
|
||||
}
|
||||
|
||||
public Money totalCost(SpecialDiscountPolicy discountPolicy) {
|
||||
return totalCost().multipliedBy(1 - applyDiscountPolicy(discountPolicy), RoundingMode.HALF_UP);
|
||||
}
|
||||
|
||||
protected double applyDiscountPolicy(SpecialDiscountPolicy discountPolicy) {
|
||||
return discountPolicy.discount(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(OrderVisitor visitor) {
|
||||
visitor.visit(this);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
package com.baeldung.ddd.order.doubledispatch;
|
||||
|
||||
public interface SpecialDiscountPolicy extends DiscountPolicy {
|
||||
double discount(SpecialOrder order);
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package com.baeldung.ddd.order.doubledispatch;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.baeldung.ddd.order.OrderLine;
|
||||
import com.baeldung.ddd.order.doubledispatch.visitor.OrderVisitor;
|
||||
|
||||
public class SpecialOrder extends Order {
|
||||
|
||||
private boolean eligibleForExtraDiscount;
|
||||
|
||||
public SpecialOrder(List<OrderLine> orderLines) {
|
||||
super(orderLines);
|
||||
this.eligibleForExtraDiscount = false;
|
||||
}
|
||||
|
||||
public SpecialOrder(List<OrderLine> orderLines, boolean eligibleForSpecialDiscount) {
|
||||
super(orderLines);
|
||||
this.eligibleForExtraDiscount = eligibleForSpecialDiscount;
|
||||
}
|
||||
|
||||
public boolean isEligibleForExtraDiscount() {
|
||||
return eligibleForExtraDiscount;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected double applyDiscountPolicy(SpecialDiscountPolicy discountPolicy) {
|
||||
return discountPolicy.discount(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(OrderVisitor visitor) {
|
||||
visitor.visit(this);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
package com.baeldung.ddd.order.doubledispatch.visitor;
|
||||
|
||||
import com.baeldung.ddd.order.doubledispatch.Order;
|
||||
import com.baeldung.ddd.order.doubledispatch.SpecialOrder;
|
||||
|
||||
public class HtmlOrderViewCreator implements OrderVisitor {
|
||||
|
||||
private String html;
|
||||
|
||||
public String getHtml() {
|
||||
return html;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visit(Order order) {
|
||||
html = String.format("<p>Regular order total cost: %s</p>", order.totalCost());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visit(SpecialOrder order) {
|
||||
html = String.format("<h1>Special Order</h1><p>total cost: %s</p>", order.totalCost());
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
package com.baeldung.ddd.order.doubledispatch.visitor;
|
||||
|
||||
import com.baeldung.ddd.order.doubledispatch.Order;
|
||||
import com.baeldung.ddd.order.doubledispatch.SpecialOrder;
|
||||
|
||||
public interface OrderVisitor {
|
||||
void visit(Order order);
|
||||
void visit(SpecialOrder order);
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
package com.baeldung.ddd.order.doubledispatch.visitor;
|
||||
|
||||
public interface Visitable<V> {
|
||||
void accept(V visitor);
|
||||
}
|
|
@ -92,7 +92,7 @@ class JpaOrder {
|
|||
}
|
||||
|
||||
void removeLineItem(int line) {
|
||||
JpaOrderLine removedLine = orderLines.remove(line);
|
||||
orderLines.remove(line);
|
||||
}
|
||||
|
||||
void setCurrencyUnit(String currencyUnit) {
|
||||
|
|
|
@ -15,7 +15,7 @@ class JpaProduct {
|
|||
public JpaProduct(BigDecimal price, String currencyUnit) {
|
||||
super();
|
||||
this.price = price;
|
||||
currencyUnit = currencyUnit;
|
||||
this.currencyUnit = currencyUnit;
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.ddd.order;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.joda.money.CurrencyUnit;
|
||||
import org.joda.money.Money;
|
||||
|
||||
public class OrderFixtureUtils {
|
||||
public static List<OrderLine> anyOrderLines() {
|
||||
return Arrays.asList(new OrderLine(new Product(Money.of(CurrencyUnit.USD, 100)), 1));
|
||||
}
|
||||
|
||||
public static List<OrderLine> orderLineItemsWorthNDollars(int totalCost) {
|
||||
return Arrays.asList(new OrderLine(new Product(Money.of(CurrencyUnit.USD, totalCost)), 1));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,77 @@
|
|||
package com.baeldung.ddd.order.doubledispatch;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.joda.money.CurrencyUnit;
|
||||
import org.joda.money.Money;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.baeldung.ddd.order.OrderFixtureUtils;
|
||||
|
||||
public class DoubleDispatchDiscountPolicyUnitTest {
|
||||
// @formatter:off
|
||||
@DisplayName(
|
||||
"given regular order with items worth $100 total, " +
|
||||
"when apply 10% discount policy, " +
|
||||
"then cost after discount is $90"
|
||||
)
|
||||
// @formatter:on
|
||||
@Test
|
||||
void test() throws Exception {
|
||||
// given
|
||||
Order order = new Order(OrderFixtureUtils.orderLineItemsWorthNDollars(100));
|
||||
SpecialDiscountPolicy discountPolicy = new SpecialDiscountPolicy() {
|
||||
|
||||
@Override
|
||||
public double discount(Order order) {
|
||||
return 0.10;
|
||||
}
|
||||
|
||||
@Override
|
||||
public double discount(SpecialOrder order) {
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
|
||||
// when
|
||||
Money totalCostAfterDiscount = order.totalCost(discountPolicy);
|
||||
|
||||
// then
|
||||
assertThat(totalCostAfterDiscount).isEqualTo(Money.of(CurrencyUnit.USD, 90));
|
||||
}
|
||||
|
||||
// @formatter:off
|
||||
@DisplayName(
|
||||
"given special order eligible for extra discount with items worth $100 total, " +
|
||||
"when apply 20% discount policy for extra discount orders, " +
|
||||
"then cost after discount is $80"
|
||||
)
|
||||
// @formatter:on
|
||||
@Test
|
||||
void test1() throws Exception {
|
||||
// given
|
||||
boolean eligibleForExtraDiscount = true;
|
||||
Order order = new SpecialOrder(OrderFixtureUtils.orderLineItemsWorthNDollars(100), eligibleForExtraDiscount);
|
||||
SpecialDiscountPolicy discountPolicy = new SpecialDiscountPolicy() {
|
||||
|
||||
@Override
|
||||
public double discount(Order order) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public double discount(SpecialOrder order) {
|
||||
if (order.isEligibleForExtraDiscount())
|
||||
return 0.20;
|
||||
return 0.10;
|
||||
}
|
||||
};
|
||||
|
||||
// when
|
||||
Money totalCostAfterDiscount = order.totalCost(discountPolicy);
|
||||
|
||||
// then
|
||||
assertThat(totalCostAfterDiscount).isEqualTo(Money.of(CurrencyUnit.USD, 80.00));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
package com.baeldung.ddd.order.doubledispatch;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.baeldung.ddd.order.doubledispatch.Order;
|
||||
import com.baeldung.ddd.order.OrderFixtureUtils;
|
||||
import com.baeldung.ddd.order.OrderLine;
|
||||
import com.baeldung.ddd.order.doubledispatch.visitor.HtmlOrderViewCreator;
|
||||
|
||||
public class HtmlOrderViewCreatorUnitTest {
|
||||
// @formatter:off
|
||||
@DisplayName(
|
||||
"given collection of regular and special orders, " +
|
||||
"when create HTML view using visitor for each order, " +
|
||||
"then the dedicated view is created for each order"
|
||||
)
|
||||
// @formatter:on
|
||||
@Test
|
||||
void test() throws Exception {
|
||||
// given
|
||||
List<OrderLine> anyOrderLines = OrderFixtureUtils.anyOrderLines();
|
||||
List<Order> orders = Arrays.asList(new Order(anyOrderLines), new SpecialOrder(anyOrderLines));
|
||||
HtmlOrderViewCreator htmlOrderViewCreator = new HtmlOrderViewCreator();
|
||||
|
||||
// when
|
||||
orders.get(0)
|
||||
.accept(htmlOrderViewCreator);
|
||||
String regularOrderHtml = htmlOrderViewCreator.getHtml();
|
||||
orders.get(1)
|
||||
.accept(htmlOrderViewCreator);
|
||||
String specialOrderHtml = htmlOrderViewCreator.getHtml();
|
||||
|
||||
// then
|
||||
assertThat(regularOrderHtml).containsPattern("<p>Regular order total cost: .*</p>");
|
||||
assertThat(specialOrderHtml).containsPattern("<h1>Special Order</h1><p>total cost: .*</p>");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,50 @@
|
|||
package com.baeldung.ddd.order.doubledispatch;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.baeldung.ddd.order.doubledispatch.Order;
|
||||
import com.baeldung.ddd.order.OrderFixtureUtils;
|
||||
import com.baeldung.ddd.order.OrderLine;
|
||||
import com.baeldung.ddd.order.doubledispatch.SpecialDiscountPolicy;
|
||||
import com.baeldung.ddd.order.doubledispatch.SpecialOrder;
|
||||
|
||||
public class MethodOverloadExampleUnitTest {
|
||||
// @formatter:off
|
||||
@DisplayName(
|
||||
"given discount policy accepting special orders, " +
|
||||
"when apply the policy on special order declared as regular order, " +
|
||||
"then regular discount method is used"
|
||||
)
|
||||
// @formatter:on
|
||||
@Test
|
||||
void test() throws Exception {
|
||||
// given
|
||||
SpecialDiscountPolicy specialPolicy = new SpecialDiscountPolicy() {
|
||||
@Override
|
||||
public double discount(Order order) {
|
||||
return 0.01;
|
||||
}
|
||||
|
||||
@Override
|
||||
public double discount(SpecialOrder order) {
|
||||
return 0.10;
|
||||
}
|
||||
};
|
||||
Order specialOrder = new SpecialOrder(anyOrderLines());
|
||||
|
||||
// when
|
||||
double discount = specialPolicy.discount(specialOrder);
|
||||
|
||||
// then
|
||||
assertThat(discount).isEqualTo(0.01);
|
||||
}
|
||||
|
||||
private List<OrderLine> anyOrderLines() {
|
||||
return OrderFixtureUtils.anyOrderLines();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
package com.baeldung.ddd.order.doubledispatch;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.baeldung.ddd.order.OrderFixtureUtils;
|
||||
|
||||
public class SingleDispatchDiscountPolicyUnitTest {
|
||||
// @formatter:off
|
||||
@DisplayName(
|
||||
"given two discount policies, " +
|
||||
"when use these policies, " +
|
||||
"then single dispatch chooses the implementation based on runtime type"
|
||||
)
|
||||
// @formatter:on
|
||||
@Test
|
||||
void test() throws Exception {
|
||||
// given
|
||||
DiscountPolicy flatPolicy = new FlatDiscountPolicy();
|
||||
DiscountPolicy amountPolicy = new AmountBasedDiscountPolicy();
|
||||
Order orderWorth501Dollars = orderWorthNDollars(501);
|
||||
|
||||
// when
|
||||
double flatDiscount = flatPolicy.discount(orderWorth501Dollars);
|
||||
double amountDiscount = amountPolicy.discount(orderWorth501Dollars);
|
||||
|
||||
// then
|
||||
assertThat(flatDiscount).isEqualTo(0.01);
|
||||
assertThat(amountDiscount).isEqualTo(0.1);
|
||||
}
|
||||
|
||||
private Order orderWorthNDollars(int totalCost) {
|
||||
return new Order(OrderFixtureUtils.orderLineItemsWorthNDollars(totalCost));
|
||||
}
|
||||
}
|
|
@ -1,4 +1,8 @@
|
|||
# Guava
|
||||
|
||||
### Relevant Articles:
|
||||
## Relevant Articles:
|
||||
|
||||
- [Guava – Sets](http://www.baeldung.com/guava-sets)
|
||||
- [Guide to Guava RangeSet](http://www.baeldung.com/guava-rangeset)
|
||||
- [Guava Set + Function = Map](http://www.baeldung.com/guava-set-function-map-tutorial)
|
||||
- [Guide to Guava Multiset](https://www.baeldung.com/guava-multiset)
|
||||
|
|
|
@ -1,14 +1,9 @@
|
|||
package org.baeldung.guava;
|
||||
|
||||
import java.util.AbstractMap;
|
||||
import java.util.AbstractSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.WeakHashMap;
|
||||
|
||||
import com.google.common.base.Function;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class GuavaMapFromSet<K, V> extends AbstractMap<K, V> {
|
||||
|
||||
private class SingleEntry implements Entry<K, V> {
|
|
@ -1,15 +1,14 @@
|
|||
package org.baeldung.guava;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import com.google.common.base.Function;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.base.Function;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class GuavaMapFromSetUnitTest {
|
||||
|
|
@ -1,13 +1,12 @@
|
|||
package org.baeldung.guava;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import org.junit.Test;
|
||||
import com.google.common.collect.ImmutableRangeSet;
|
||||
import com.google.common.collect.Range;
|
||||
import com.google.common.collect.RangeSet;
|
||||
import com.google.common.collect.TreeRangeSet;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class GuavaRangeSetUnitTest {
|
||||
|
||||
|
@ -122,6 +121,5 @@ public class GuavaRangeSetUnitTest {
|
|||
.add(Range.closed(0, 2))
|
||||
.add(Range.closed(3, 5))
|
||||
.add(Range.closed(5, 8)).build();
|
||||
|
||||
}
|
||||
}
|
|
@ -0,0 +1,131 @@
|
|||
package org.baeldung.guava;
|
||||
|
||||
import com.google.common.base.Function;
|
||||
import com.google.common.base.Joiner;
|
||||
import com.google.common.collect.*;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.hamcrest.Matchers.contains;
|
||||
import static org.hamcrest.Matchers.containsInAnyOrder;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class GuavaSetOperationsUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenCalculatingUnionOfSets_thenCorrect() {
|
||||
final Set<Character> first = ImmutableSet.of('a', 'b', 'c');
|
||||
final Set<Character> second = ImmutableSet.of('b', 'c', 'd');
|
||||
|
||||
final Set<Character> union = Sets.union(first, second);
|
||||
assertThat(union, containsInAnyOrder('a', 'b', 'c', 'd'));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCalculatingCartesianProductOfSets_thenCorrect() {
|
||||
final Set<Character> first = ImmutableSet.of('a', 'b');
|
||||
final Set<Character> second = ImmutableSet.of('c', 'd');
|
||||
final Set<List<Character>> result = Sets.cartesianProduct(ImmutableList.of(first, second));
|
||||
|
||||
final Function<List<Character>, String> func = new Function<List<Character>, String>() {
|
||||
@Override
|
||||
public final String apply(final List<Character> input) {
|
||||
return Joiner
|
||||
.on(" ").join(input);
|
||||
}
|
||||
};
|
||||
|
||||
final Iterable<String> joined = Iterables.transform(result, func);
|
||||
assertThat(joined, containsInAnyOrder("a c", "a d", "b c", "b d"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCalculatingSetIntersection_thenCorrect() {
|
||||
final Set<Character> first = ImmutableSet.of('a', 'b', 'c');
|
||||
final Set<Character> second = ImmutableSet.of('b', 'c', 'd');
|
||||
|
||||
final Set<Character> intersection = Sets.intersection(first, second);
|
||||
assertThat(intersection, containsInAnyOrder('b', 'c'));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCalculatingSetSymmetricDifference_thenCorrect() {
|
||||
final Set<Character> first = ImmutableSet.of('a', 'b', 'c');
|
||||
final Set<Character> second = ImmutableSet.of('b', 'c', 'd');
|
||||
|
||||
final Set<Character> intersection = Sets.symmetricDifference(first, second);
|
||||
assertThat(intersection, containsInAnyOrder('a', 'd'));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCalculatingPowerSet_thenCorrect() {
|
||||
final Set<Character> chars = ImmutableSet.of('a', 'b');
|
||||
final Set<Set<Character>> result = Sets.powerSet(chars);
|
||||
|
||||
final Set<Character> empty = ImmutableSet.<Character> builder().build();
|
||||
final Set<Character> a = ImmutableSet.of('a');
|
||||
final Set<Character> b = ImmutableSet.of('b');
|
||||
final Set<Character> aB = ImmutableSet.of('a', 'b');
|
||||
|
||||
assertThat(result, contains(empty, a, b, aB));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatingRangeOfIntegersSet_thenCreated() {
|
||||
final int start = 10;
|
||||
final int end = 30;
|
||||
final ContiguousSet<Integer> set = ContiguousSet.create(Range.closed(start, end), DiscreteDomain.integers());
|
||||
|
||||
assertEquals(21, set.size());
|
||||
assertEquals(10, set.first().intValue());
|
||||
assertEquals(30, set.last().intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingRangeSet_thenCorrect() {
|
||||
final RangeSet<Integer> rangeSet = TreeRangeSet.create();
|
||||
rangeSet.add(Range.closed(1, 10));
|
||||
rangeSet.add(Range.closed(12, 15));
|
||||
|
||||
assertEquals(2, rangeSet.asRanges().size());
|
||||
|
||||
rangeSet.add(Range.closed(10, 12));
|
||||
assertTrue(rangeSet.encloses(Range.closed(1, 15)));
|
||||
assertEquals(1, rangeSet.asRanges().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenInsertDuplicatesInMultiSet_thenInserted() {
|
||||
final Multiset<String> names = HashMultiset.create();
|
||||
names.add("John");
|
||||
names.add("Adam", 3);
|
||||
names.add("John");
|
||||
|
||||
assertEquals(2, names.count("John"));
|
||||
names.remove("John");
|
||||
assertEquals(1, names.count("John"));
|
||||
|
||||
assertEquals(3, names.count("Adam"));
|
||||
names.remove("Adam", 2);
|
||||
assertEquals(1, names.count("Adam"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetTopOcurringElementsWithMultiSet_thenCorrect() {
|
||||
final Multiset<String> names = HashMultiset.create();
|
||||
names.add("John");
|
||||
names.add("Adam", 5);
|
||||
names.add("Jane");
|
||||
names.add("Tom", 2);
|
||||
|
||||
final Set<String> sorted = Multisets.copyHighestCountFirst(names).elementSet();
|
||||
final List<String> topTwo = Lists.newArrayList(sorted).subList(0, 2);
|
||||
assertEquals(2, topTwo.size());
|
||||
assertEquals("Adam", topTwo.get(0));
|
||||
assertEquals("Tom", topTwo.get(1));
|
||||
}
|
||||
}
|
|
@ -11,13 +11,10 @@
|
|||
- [Filtering and Transforming Collections in Guava](http://www.baeldung.com/guava-filter-and-transform-a-collection)
|
||||
- [Guava – Join and Split Collections](http://www.baeldung.com/guava-joiner-and-splitter-tutorial)
|
||||
- [Guava – Lists](http://www.baeldung.com/guava-lists)
|
||||
- [Guava – Sets](http://www.baeldung.com/guava-sets)
|
||||
- [Guava – Maps](http://www.baeldung.com/guava-maps)
|
||||
- [Guide to Guava Multimap](http://www.baeldung.com/guava-multimap)
|
||||
- [Guide to Guava RangeSet](http://www.baeldung.com/guava-rangeset)
|
||||
- [Guide to Guava RangeMap](http://www.baeldung.com/guava-rangemap)
|
||||
- [Guide to Guava MinMaxPriorityQueue and EvictingQueue](http://www.baeldung.com/guava-minmax-priority-queue-and-evicting-queue)
|
||||
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
|
||||
- [Guava Set + Function = Map](http://www.baeldung.com/guava-set-function-map-tutorial)
|
||||
- [Guide to Guava Table](http://www.baeldung.com/guava-table)
|
||||
- [Guide to Guava ClassToInstanceMap](http://www.baeldung.com/guava-class-to-instance-map)
|
|
@ -111,120 +111,6 @@ public class GuavaCollectionTypesUnitTest {
|
|||
assertThat(immutable, contains("John", "Adam", "Jane", "Tom"));
|
||||
}
|
||||
|
||||
// sets
|
||||
|
||||
@Test
|
||||
public void whenCalculateUnionOfSets_thenCorrect() {
|
||||
final Set<Character> first = ImmutableSet.of('a', 'b', 'c');
|
||||
final Set<Character> second = ImmutableSet.of('b', 'c', 'd');
|
||||
|
||||
final Set<Character> union = Sets.union(first, second);
|
||||
assertThat(union, containsInAnyOrder('a', 'b', 'c', 'd'));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCalculateSetsProduct_thenCorrect() {
|
||||
final Set<Character> first = ImmutableSet.of('a', 'b');
|
||||
final Set<Character> second = ImmutableSet.of('c', 'd');
|
||||
final Set<List<Character>> result = Sets.cartesianProduct(ImmutableList.of(first, second));
|
||||
|
||||
final Function<List<Character>, String> func = new Function<List<Character>, String>() {
|
||||
@Override
|
||||
public final String apply(final List<Character> input) {
|
||||
return Joiner.on(" ").join(input);
|
||||
}
|
||||
};
|
||||
|
||||
final Iterable<String> joined = Iterables.transform(result, func);
|
||||
assertThat(joined, containsInAnyOrder("a c", "a d", "b c", "b d"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCalculatingSetIntersection_thenCorrect() {
|
||||
final Set<Character> first = ImmutableSet.of('a', 'b', 'c');
|
||||
final Set<Character> second = ImmutableSet.of('b', 'c', 'd');
|
||||
|
||||
final Set<Character> intersection = Sets.intersection(first, second);
|
||||
assertThat(intersection, containsInAnyOrder('b', 'c'));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCalculatingSetSymmetricDifference_thenCorrect() {
|
||||
final Set<Character> first = ImmutableSet.of('a', 'b', 'c');
|
||||
final Set<Character> second = ImmutableSet.of('b', 'c', 'd');
|
||||
|
||||
final Set<Character> intersection = Sets.symmetricDifference(first, second);
|
||||
assertThat(intersection, containsInAnyOrder('a', 'd'));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCalculatingPowerSet_thenCorrect() {
|
||||
final Set<Character> chars = ImmutableSet.of('a', 'b');
|
||||
final Set<Set<Character>> result = Sets.powerSet(chars);
|
||||
|
||||
final Set<Character> empty = ImmutableSet.<Character> builder().build();
|
||||
final Set<Character> a = ImmutableSet.of('a');
|
||||
final Set<Character> b = ImmutableSet.of('b');
|
||||
final Set<Character> aB = ImmutableSet.of('a', 'b');
|
||||
|
||||
assertThat(result, contains(empty, a, b, aB));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreateRangeOfIntegersSet_thenCreated() {
|
||||
final int start = 10;
|
||||
final int end = 30;
|
||||
final ContiguousSet<Integer> set = ContiguousSet.create(Range.closed(start, end), DiscreteDomain.integers());
|
||||
|
||||
assertEquals(21, set.size());
|
||||
assertEquals(10, set.first().intValue());
|
||||
assertEquals(30, set.last().intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreateRangeSet_thenCreated() {
|
||||
final RangeSet<Integer> rangeSet = TreeRangeSet.create();
|
||||
rangeSet.add(Range.closed(1, 10));
|
||||
rangeSet.add(Range.closed(12, 15));
|
||||
|
||||
assertEquals(2, rangeSet.asRanges().size());
|
||||
|
||||
rangeSet.add(Range.closed(10, 12));
|
||||
assertTrue(rangeSet.encloses(Range.closed(1, 15)));
|
||||
assertEquals(1, rangeSet.asRanges().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenInsertDuplicatesInMultiSet_thenInserted() {
|
||||
final Multiset<String> names = HashMultiset.create();
|
||||
names.add("John");
|
||||
names.add("Adam", 3);
|
||||
names.add("John");
|
||||
|
||||
assertEquals(2, names.count("John"));
|
||||
names.remove("John");
|
||||
assertEquals(1, names.count("John"));
|
||||
|
||||
assertEquals(3, names.count("Adam"));
|
||||
names.remove("Adam", 2);
|
||||
assertEquals(1, names.count("Adam"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetTopUsingMultiSet_thenCorrect() {
|
||||
final Multiset<String> names = HashMultiset.create();
|
||||
names.add("John");
|
||||
names.add("Adam", 5);
|
||||
names.add("Jane");
|
||||
names.add("Tom", 2);
|
||||
|
||||
final Set<String> sorted = Multisets.copyHighestCountFirst(names).elementSet();
|
||||
final List<String> topTwo = Lists.newArrayList(sorted).subList(0, 2);
|
||||
assertEquals(2, topTwo.size());
|
||||
assertEquals("Adam", topTwo.get(0));
|
||||
assertEquals("Tom", topTwo.get(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreateImmutableMap_thenCreated() {
|
||||
final Map<String, Integer> salary = ImmutableMap.<String, Integer> builder().put("John", 1000).put("Jane", 1500).put("Adam", 2000).put("Tom", 2000).build();
|
||||
|
|
|
@ -1,2 +1,3 @@
|
|||
## Relevant Articles:
|
||||
- [Converting Between LocalDate and XMLGregorianCalendar](https://www.baeldung.com/java-localdate-to-xmlgregoriancalendar)
|
||||
- [Convert Time to Milliseconds in Java](https://www.baeldung.com/java-time-milliseconds)
|
||||
|
|
|
@ -0,0 +1,5 @@
|
|||
## Relevant Articles
|
||||
|
||||
- [Java Localization – Formatting Messages](https://www.baeldung.com/java-localization-messages-formatting)
|
||||
- [Check If a String Contains a Substring](https://www.baeldung.com/java-string-contains-substring)
|
||||
- [Removing Stopwords from a String in Java](https://www.baeldung.com/java-string-remove-stopwords)
|
|
@ -15,28 +15,6 @@
|
|||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
<version>${commons-io.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>${log4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-codec</groupId>
|
||||
<artifactId>commons-codec</artifactId>
|
||||
<version>${commons-codec.version}</version>
|
||||
</dependency>
|
||||
<!-- test scoped -->
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
|
@ -57,11 +35,6 @@
|
|||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.vdurmont</groupId>
|
||||
<artifactId>emoji-java</artifactId>
|
||||
<version>${emoji-java.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
|
@ -73,38 +46,18 @@
|
|||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<version>${junit-jupiter-api.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-library</artifactId>
|
||||
<version>${org.hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Added for password generation -->
|
||||
<dependency>
|
||||
<groupId>org.passay</groupId>
|
||||
<artifactId>passay</artifactId>
|
||||
<version>${passay.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-text</artifactId>
|
||||
<version>${commons-text.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.ahocorasick</groupId>
|
||||
<artifactId>ahocorasick</artifactId>
|
||||
<version>${ahocorasick.version}</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
@ -131,18 +84,10 @@
|
|||
</build>
|
||||
|
||||
<properties>
|
||||
<!-- util -->
|
||||
<commons-lang3.version>3.8.1</commons-lang3.version>
|
||||
<commons-codec.version>1.10</commons-codec.version>
|
||||
<!-- testing -->
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<icu4j.version>61.1</icu4j.version>
|
||||
<guava.version>27.0.1-jre</guava.version>
|
||||
<emoji-java.version>4.0.0</emoji-java.version>
|
||||
<junit-jupiter-api.version>5.3.1</junit-jupiter-api.version>
|
||||
<passay.version>1.3.1</passay.version>
|
||||
<commons-text.version>1.4</commons-text.version>
|
||||
<ahocorasick.version>0.4.0</ahocorasick.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,73 @@
|
|||
package com.baeldung.string.performance;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.openjdk.jmh.annotations.Benchmark;
|
||||
import org.openjdk.jmh.annotations.BenchmarkMode;
|
||||
import org.openjdk.jmh.annotations.Fork;
|
||||
import org.openjdk.jmh.annotations.Mode;
|
||||
import org.openjdk.jmh.annotations.OutputTimeUnit;
|
||||
import org.openjdk.jmh.annotations.Scope;
|
||||
import org.openjdk.jmh.annotations.Setup;
|
||||
import org.openjdk.jmh.annotations.State;
|
||||
|
||||
|
||||
@Fork(value = 3, warmups = 1)
|
||||
@State(Scope.Benchmark)
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.MILLISECONDS)
|
||||
public class RemovingStopwordsPerformanceComparison {
|
||||
|
||||
private String data;
|
||||
|
||||
private List<String> stopwords;
|
||||
|
||||
private String stopwordsRegex;
|
||||
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
org.openjdk.jmh.Main.main(args);
|
||||
}
|
||||
|
||||
@Setup
|
||||
public void setup() throws IOException {
|
||||
data = new String(Files.readAllBytes(Paths.get("src/main/resources/shakespeare-hamlet.txt")));
|
||||
data = data.toLowerCase();
|
||||
stopwords = Files.readAllLines(Paths.get("src/main/resources/english_stopwords.txt"));
|
||||
stopwordsRegex = stopwords.stream().collect(Collectors.joining("|", "\\b(", ")\\b\\s?"));
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public String removeManually() {
|
||||
String[] allWords = data.split(" ");
|
||||
StringBuilder builder = new StringBuilder();
|
||||
for(String word:allWords) {
|
||||
if(! stopwords.contains(word)) {
|
||||
builder.append(word);
|
||||
builder.append(' ');
|
||||
}
|
||||
}
|
||||
return builder.toString().trim();
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public String removeAll() {
|
||||
ArrayList<String> allWords = Stream.of(data.split(" "))
|
||||
.collect(Collectors.toCollection(ArrayList<String>::new));
|
||||
allWords.removeAll(stopwords);
|
||||
return allWords.stream().collect(Collectors.joining(" "));
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public String replaceRegex() {
|
||||
return data.replaceAll(stopwordsRegex, "");
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,127 @@
|
|||
i
|
||||
me
|
||||
my
|
||||
myself
|
||||
we
|
||||
our
|
||||
ours
|
||||
ourselves
|
||||
you
|
||||
your
|
||||
yours
|
||||
yourself
|
||||
yourselves
|
||||
he
|
||||
him
|
||||
his
|
||||
himself
|
||||
she
|
||||
her
|
||||
hers
|
||||
herself
|
||||
it
|
||||
its
|
||||
itself
|
||||
they
|
||||
them
|
||||
their
|
||||
theirs
|
||||
themselves
|
||||
what
|
||||
which
|
||||
who
|
||||
whom
|
||||
this
|
||||
that
|
||||
these
|
||||
those
|
||||
am
|
||||
is
|
||||
are
|
||||
was
|
||||
were
|
||||
be
|
||||
been
|
||||
being
|
||||
have
|
||||
has
|
||||
had
|
||||
having
|
||||
do
|
||||
does
|
||||
did
|
||||
doing
|
||||
a
|
||||
an
|
||||
the
|
||||
and
|
||||
but
|
||||
if
|
||||
or
|
||||
because
|
||||
as
|
||||
until
|
||||
while
|
||||
of
|
||||
at
|
||||
by
|
||||
for
|
||||
with
|
||||
about
|
||||
against
|
||||
between
|
||||
into
|
||||
through
|
||||
during
|
||||
before
|
||||
after
|
||||
above
|
||||
below
|
||||
to
|
||||
from
|
||||
up
|
||||
down
|
||||
in
|
||||
out
|
||||
on
|
||||
off
|
||||
over
|
||||
under
|
||||
again
|
||||
further
|
||||
then
|
||||
once
|
||||
here
|
||||
there
|
||||
when
|
||||
where
|
||||
why
|
||||
how
|
||||
all
|
||||
any
|
||||
both
|
||||
each
|
||||
few
|
||||
more
|
||||
most
|
||||
other
|
||||
some
|
||||
such
|
||||
no
|
||||
nor
|
||||
not
|
||||
only
|
||||
own
|
||||
same
|
||||
so
|
||||
than
|
||||
too
|
||||
very
|
||||
s
|
||||
t
|
||||
can
|
||||
will
|
||||
just
|
||||
don
|
||||
should
|
||||
now
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,58 @@
|
|||
package com.baeldung.initialization;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class StringInitializationUnitTest {
|
||||
|
||||
private String fieldString;
|
||||
|
||||
void printDeclaredOnlyString() {
|
||||
String localVarString = null;
|
||||
|
||||
System.out.println(localVarString); // compilation error
|
||||
System.out.println(fieldString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDeclaredFeldStringAndNullString_thenCompareEquals() {
|
||||
String localVarString = null;
|
||||
|
||||
assertEquals(fieldString, localVarString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoStringsWithSameLiteral_thenCompareReferencesEquals() {
|
||||
String literalOne = "Baeldung";
|
||||
String literalTwo = "Baeldung";
|
||||
|
||||
assertTrue(literalOne == literalTwo);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoStringsUsingNew_thenCompareReferencesNotEquals() {
|
||||
String newStringOne = new String("Baeldung");
|
||||
String newStringTwo = new String("Baeldung");
|
||||
|
||||
assertFalse(newStringOne == newStringTwo);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyLiteralStringsAndNewObject_thenCompareEquals() {
|
||||
String emptyLiteral = "";
|
||||
String emptyNewString = new String("");
|
||||
|
||||
assertEquals(emptyLiteral, emptyNewString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyStringObjects_thenCompareEquals() {
|
||||
String emptyNewString = new String("");
|
||||
String emptyNewStringTwo = new String();
|
||||
|
||||
assertEquals(emptyNewString, emptyNewStringTwo);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,60 @@
|
|||
package com.baeldung.string;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
public class RemoveStopwordsUnitTest {
|
||||
final String original = "The quick brown fox jumps over the lazy dog";
|
||||
final String target = "quick brown fox jumps lazy dog";
|
||||
static List<String> stopwords;
|
||||
|
||||
@BeforeClass
|
||||
public static void loadStopwords() throws IOException {
|
||||
stopwords = Files.readAllLines(Paths.get("src/main/resources/english_stopwords.txt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRemoveStopwordsManually_thenSuccess() {
|
||||
String[] allWords = original.toLowerCase()
|
||||
.split(" ");
|
||||
StringBuilder builder = new StringBuilder();
|
||||
for (String word : allWords) {
|
||||
if (!stopwords.contains(word)) {
|
||||
builder.append(word);
|
||||
builder.append(' ');
|
||||
}
|
||||
}
|
||||
|
||||
String result = builder.toString().trim();
|
||||
assertEquals(result, target);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRemoveStopwordsUsingRemoveAll_thenSuccess() {
|
||||
ArrayList<String> allWords = Stream.of(original.toLowerCase()
|
||||
.split(" "))
|
||||
.collect(Collectors.toCollection(ArrayList<String>::new));
|
||||
allWords.removeAll(stopwords);
|
||||
String result = allWords.stream().collect(Collectors.joining(" "));
|
||||
assertEquals(result, target);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRemoveStopwordsUsingRegex_thenSuccess() {
|
||||
String stopwordsRegex = stopwords.stream()
|
||||
.collect(Collectors.joining("|", "\\b(", ")\\b\\s?"));
|
||||
String result = original.toLowerCase().replaceAll(stopwordsRegex, "");
|
||||
assertEquals(result, target);
|
||||
}
|
||||
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue