[BAEL-9555] - Created a core-java-modules folder
This commit is contained in:
26
core-java-modules/core-java-8/.gitignore
vendored
Normal file
26
core-java-modules/core-java-8/.gitignore
vendored
Normal file
@@ -0,0 +1,26 @@
|
||||
*.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
|
||||
*.txt
|
||||
backup-pom.xml
|
||||
/bin/
|
||||
/temp
|
||||
|
||||
#IntelliJ specific
|
||||
.idea/
|
||||
*.iml
|
||||
42
core-java-modules/core-java-8/README.md
Normal file
42
core-java-modules/core-java-8/README.md
Normal file
@@ -0,0 +1,42 @@
|
||||
=========
|
||||
|
||||
## Core Java 8 Cookbooks and Examples
|
||||
|
||||
### Relevant Articles:
|
||||
- [Guide to Java 8’s Collectors](http://www.baeldung.com/java-8-collectors)
|
||||
- [Functional Interfaces in Java 8](http://www.baeldung.com/java-8-functional-interfaces)
|
||||
- [Java 8 – Powerful Comparison with Lambdas](http://www.baeldung.com/java-8-sort-lambda)
|
||||
- [New Features in Java 8](http://www.baeldung.com/java-8-new-features)
|
||||
- [Lambda Expressions and Functional Interfaces: Tips and Best Practices](http://www.baeldung.com/java-8-lambda-expressions-tips)
|
||||
- [The Double Colon Operator in Java 8](http://www.baeldung.com/java-8-double-colon-operator)
|
||||
- [Guide to Java 8 groupingBy Collector](http://www.baeldung.com/java-groupingby-collector)
|
||||
- [Strategy Design Pattern in Java 8](http://www.baeldung.com/java-strategy-pattern)
|
||||
- [Exceptions in Java 8 Lambda Expressions](http://www.baeldung.com/java-lambda-exceptions)
|
||||
- [Guide to Java 8 Comparator.comparing()](http://www.baeldung.com/java-8-comparator-comparing)
|
||||
- [Guide To Java 8 Optional](http://www.baeldung.com/java-optional)
|
||||
- [Guide to the Java 8 forEach](http://www.baeldung.com/foreach-java)
|
||||
- [The Difference Between map() and flatMap()](http://www.baeldung.com/java-difference-map-and-flatmap)
|
||||
- [Static and Default Methods in Interfaces in Java](http://www.baeldung.com/java-static-default-methods)
|
||||
- [Efficient Word Frequency Calculator in Java](http://www.baeldung.com/java-word-frequency)
|
||||
- [Introduction to Spliterator in Java](http://www.baeldung.com/java-spliterator)
|
||||
- [Java 8 Math New Methods](http://www.baeldung.com/java-8-math)
|
||||
- [Overview of Java Built-in Annotations](http://www.baeldung.com/java-default-annotations)
|
||||
- [Finding Min/Max in an Array with Java](http://www.baeldung.com/java-array-min-max)
|
||||
- [Internationalization and Localization in Java 8](http://www.baeldung.com/java-8-localization)
|
||||
- [Java Optional – orElse() vs orElseGet()](http://www.baeldung.com/java-optional-or-else-vs-or-else-get)
|
||||
- [Method Parameter Reflection in Java](http://www.baeldung.com/java-parameter-reflection)
|
||||
- [Java 8 Unsigned Arithmetic Support](http://www.baeldung.com/java-unsigned-arithmetic)
|
||||
- [Generalized Target-Type Inference in Java](http://www.baeldung.com/java-generalized-target-type-inference)
|
||||
- [Overriding System Time for Testing in Java](http://www.baeldung.com/java-override-system-time)
|
||||
- [Set the Time Zone of a Date in Java](https://www.baeldung.com/java-set-date-time-zone)
|
||||
- [An Overview of Regular Expressions Performance in Java](https://www.baeldung.com/java-regex-performance)
|
||||
- [Java Primitives versus Objects](https://www.baeldung.com/java-primitives-vs-objects)
|
||||
- [How to Use if/else Logic in Java 8 Streams](https://www.baeldung.com/java-8-streams-if-else-logic)
|
||||
- [How to Replace Many if Statements in Java](https://www.baeldung.com/java-replace-if-statements)
|
||||
- [Java @Override Annotation](https://www.baeldung.com/java-override)
|
||||
- [Java @SuppressWarnings Annotation](https://www.baeldung.com/java-suppresswarnings)
|
||||
- [Java @SafeVarargs Annotation](https://www.baeldung.com/java-safevarargs)
|
||||
- [Java @Deprecated Annotation](https://www.baeldung.com/java-deprecated)
|
||||
- [Java 8 Predicate Chain](https://www.baeldung.com/java-predicate-chain)
|
||||
- [Method References in Java](https://www.baeldung.com/java-method-references)
|
||||
- [Creating a Custom Annotation in Java](https://www.baeldung.com/java-custom-annotation)
|
||||
199
core-java-modules/core-java-8/pom.xml
Normal file
199
core-java-modules/core-java-8/pom.xml
Normal file
@@ -0,0 +1,199 @@
|
||||
<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-8</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-8</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>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
<version>${commons-io.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-math3</artifactId>
|
||||
<version>${commons-math3.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>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<!-- test scoped -->
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.jayway.awaitility</groupId>
|
||||
<artifactId>awaitility</artifactId>
|
||||
<version>${avaitility.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.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-bytecode</artifactId>
|
||||
<version>${jmh-generator.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.codepoetics</groupId>
|
||||
<artifactId>protonpack</artifactId>
|
||||
<version>${protonpack.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.vavr</groupId>
|
||||
<artifactId>vavr</artifactId>
|
||||
<version>${vavr.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>joda-time</groupId>
|
||||
<artifactId>joda-time</artifactId>
|
||||
<version>${joda.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.aspectj</groupId>
|
||||
<artifactId>aspectjrt</artifactId>
|
||||
<version>${asspectj.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.aspectj</groupId>
|
||||
<artifactId>aspectjweaver</artifactId>
|
||||
<version>${asspectj.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.powermock</groupId>
|
||||
<artifactId>powermock-module-junit4</artifactId>
|
||||
<version>${powermock.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.powermock</groupId>
|
||||
<artifactId>powermock-api-mockito2</artifactId>
|
||||
<version>${powermock.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jmockit</groupId>
|
||||
<artifactId>jmockit</artifactId>
|
||||
<version>${jmockit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-8</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
<compilerArgument>-parameters</compilerArgument>
|
||||
</configuration>
|
||||
</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>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
<configuration>
|
||||
<argLine>
|
||||
-javaagent:${settings.localRepository}/org/jmockit/jmockit/${jmockit.version}/jmockit-${jmockit.version}.jar
|
||||
</argLine>
|
||||
<disableXmlReport>true</disableXmlReport>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<!-- util -->
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
<commons-math3.version>3.6.1</commons-math3.version>
|
||||
<commons-collections4.version>4.1</commons-collections4.version>
|
||||
<collections-generic.version>4.01</collections-generic.version>
|
||||
<commons-codec.version>1.10</commons-codec.version>
|
||||
<vavr.version>0.9.0</vavr.version>
|
||||
<protonpack.version>1.13</protonpack.version>
|
||||
<joda.version>2.10</joda.version>
|
||||
<!-- testing -->
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<asspectj.version>1.8.9</asspectj.version>
|
||||
<powermock.version>2.0.0-RC.4</powermock.version>
|
||||
<jmockit.version>1.44</jmockit.version>
|
||||
<avaitility.version>1.7.0</avaitility.version>
|
||||
<jmh-core.version>1.19</jmh-core.version>
|
||||
<jmh-generator.version>1.19</jmh-generator.version>
|
||||
<spring-boot-maven-plugin.version>2.0.4.RELEASE</spring-boot-maven-plugin.version>
|
||||
<!-- plugins -->
|
||||
<maven-compiler-plugin.version>3.8.0</maven-compiler-plugin.version>
|
||||
<maven-surefire-plugin.version>2.22.1</maven-surefire-plugin.version>
|
||||
</properties>
|
||||
</project>
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.annotations;
|
||||
|
||||
@Deprecated
|
||||
class ClassWithAnnotation {
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.annotations;
|
||||
|
||||
class ClassWithDeprecatedMethod {
|
||||
|
||||
@Deprecated
|
||||
static void deprecatedMethod() {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.annotations;
|
||||
|
||||
class ClassWithSafeVarargs<T> {
|
||||
|
||||
@SafeVarargs
|
||||
final void iterateOverVarargs(T... args) {
|
||||
for (T x : args) {
|
||||
// do stuff with x
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.annotations;
|
||||
|
||||
class ClassWithSuppressWarnings {
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
void useDeprecatedMethod() {
|
||||
ClassWithDeprecatedMethod.deprecatedMethod(); // no warning is generated here
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.annotations;
|
||||
|
||||
@FunctionalInterface
|
||||
interface IntConsumer {
|
||||
|
||||
void accept(Integer number);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.annotations;
|
||||
|
||||
import java.lang.annotation.Repeatable;
|
||||
|
||||
@Repeatable(Intervals.class)
|
||||
@interface Interval {
|
||||
int hour() default 1;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.annotations;
|
||||
|
||||
public class IntervalUsage {
|
||||
|
||||
@Interval(hour = 17)
|
||||
@Interval(hour = 13)
|
||||
void doPeriodicCleanup() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.annotations;
|
||||
|
||||
@interface Intervals {
|
||||
Interval[] value();
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.annotations;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
@Inherited
|
||||
@Documented
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target({ElementType.LOCAL_VARIABLE, ElementType.FIELD})
|
||||
@interface MyAnnotation {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.annotations;
|
||||
|
||||
class MyAnnotationTarget {
|
||||
|
||||
// this is OK
|
||||
@MyAnnotation
|
||||
String someField;
|
||||
|
||||
// @MyAnnotation <- this is invalid usage!
|
||||
void doSomething() {
|
||||
|
||||
// this also works
|
||||
@MyAnnotation
|
||||
String localVariable;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.baeldung.annotations;
|
||||
|
||||
interface MyOperation {
|
||||
|
||||
void perform();
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.annotations;
|
||||
|
||||
class MyOperationImpl implements MyOperation {
|
||||
|
||||
@Override
|
||||
public void perform() {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.aspect;
|
||||
|
||||
public aspect ChangeCallsToCurrentTimeInMillisMethod {
|
||||
long around():
|
||||
call(public static native long java.lang.System.currentTimeMillis())
|
||||
&& within(user.code.base.pckg.*) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.customannotations;
|
||||
|
||||
import static java.lang.annotation.ElementType.METHOD;
|
||||
import static java.lang.annotation.RetentionPolicy.RUNTIME;
|
||||
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Retention(RUNTIME)
|
||||
@Target(METHOD)
|
||||
public @interface Init {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.customannotations;
|
||||
|
||||
import static java.lang.annotation.ElementType.FIELD;
|
||||
import static java.lang.annotation.RetentionPolicy.RUNTIME;
|
||||
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Retention(RUNTIME)
|
||||
@Target({ FIELD })
|
||||
public @interface JsonElement {
|
||||
public String key() default "";
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.customannotations;
|
||||
|
||||
import static java.lang.annotation.ElementType.TYPE;
|
||||
import static java.lang.annotation.RetentionPolicy.RUNTIME;
|
||||
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Retention(RUNTIME)
|
||||
@Target(TYPE)
|
||||
public @interface JsonSerializable {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.customannotations;
|
||||
|
||||
public class JsonSerializationException extends RuntimeException {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public JsonSerializationException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.baeldung.customannotations;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class ObjectToJsonConverter {
|
||||
public String convertToJson(Object object) throws JsonSerializationException {
|
||||
try {
|
||||
|
||||
checkIfSerializable(object);
|
||||
initializeObject(object);
|
||||
return getJsonString(object);
|
||||
|
||||
} catch (Exception e) {
|
||||
throw new JsonSerializationException(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void checkIfSerializable(Object object) {
|
||||
if (Objects.isNull(object)) {
|
||||
throw new JsonSerializationException("Can't serialize a null object");
|
||||
}
|
||||
|
||||
Class<?> clazz = object.getClass();
|
||||
if (!clazz.isAnnotationPresent(JsonSerializable.class)) {
|
||||
throw new JsonSerializationException("The class " + clazz.getSimpleName() + " is not annotated with JsonSerializable");
|
||||
}
|
||||
}
|
||||
|
||||
private void initializeObject(Object object) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
|
||||
Class<?> clazz = object.getClass();
|
||||
for (Method method : clazz.getDeclaredMethods()) {
|
||||
if (method.isAnnotationPresent(Init.class)) {
|
||||
method.setAccessible(true);
|
||||
method.invoke(object);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String getJsonString(Object object) throws IllegalArgumentException, IllegalAccessException {
|
||||
Class<?> clazz = object.getClass();
|
||||
Map<String, String> jsonElementsMap = new HashMap<>();
|
||||
for (Field field : clazz.getDeclaredFields()) {
|
||||
field.setAccessible(true);
|
||||
if (field.isAnnotationPresent(JsonElement.class)) {
|
||||
jsonElementsMap.put(getKey(field), (String) field.get(object));
|
||||
}
|
||||
}
|
||||
|
||||
String jsonString = jsonElementsMap.entrySet()
|
||||
.stream()
|
||||
.map(entry -> "\"" + entry.getKey() + "\":\"" + entry.getValue() + "\"")
|
||||
.collect(Collectors.joining(","));
|
||||
return "{" + jsonString + "}";
|
||||
}
|
||||
|
||||
private String getKey(Field field) {
|
||||
String value = field.getAnnotation(JsonElement.class)
|
||||
.key();
|
||||
return value.isEmpty() ? field.getName() : value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.baeldung.customannotations;
|
||||
|
||||
@JsonSerializable
|
||||
public class Person {
|
||||
@JsonElement
|
||||
private String firstName;
|
||||
@JsonElement
|
||||
private String lastName;
|
||||
@JsonElement(key = "personAge")
|
||||
private String age;
|
||||
|
||||
private String address;
|
||||
|
||||
public Person(String firstName, String lastName) {
|
||||
super();
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public Person(String firstName, String lastName, String age) {
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
@Init
|
||||
private void initNames() {
|
||||
this.firstName = this.firstName.substring(0, 1)
|
||||
.toUpperCase() + this.firstName.substring(1);
|
||||
this.lastName = this.lastName.substring(0, 1)
|
||||
.toUpperCase() + this.lastName.substring(1);
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public String getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(String age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public String getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(String address) {
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.defaultstaticinterfacemethods.application;
|
||||
|
||||
import com.baeldung.defaultstaticinterfacemethods.model.Car;
|
||||
import com.baeldung.defaultstaticinterfacemethods.model.Vehicle;
|
||||
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
Vehicle car = new Car("BMW");
|
||||
System.out.println(car.getBrand());
|
||||
System.out.println(car.speedUp());
|
||||
System.out.println(car.slowDown());
|
||||
System.out.println(car.turnAlarmOn());
|
||||
System.out.println(car.turnAlarmOff());
|
||||
System.out.println(Vehicle.getHorsePower(2500, 480));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.defaultstaticinterfacemethods.model;
|
||||
|
||||
public interface Alarm {
|
||||
|
||||
default String turnAlarmOn() {
|
||||
return "Turning the alarm on.";
|
||||
}
|
||||
|
||||
default String turnAlarmOff() {
|
||||
return "Turning the alarm off.";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.defaultstaticinterfacemethods.model;
|
||||
|
||||
public class Car implements Vehicle {
|
||||
|
||||
private final String brand;
|
||||
|
||||
public Car(String brand) {
|
||||
this.brand = brand;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getBrand() {
|
||||
return brand;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String speedUp() {
|
||||
return "The car is speeding up.";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String slowDown() {
|
||||
return "The car is slowing down.";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.defaultstaticinterfacemethods.model;
|
||||
|
||||
public class Motorbike implements Vehicle {
|
||||
|
||||
private final String brand;
|
||||
|
||||
public Motorbike(String brand) {
|
||||
this.brand = brand;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getBrand() {
|
||||
return brand;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String speedUp() {
|
||||
return "The motorbike is speeding up.";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String slowDown() {
|
||||
return "The motorbike is slowing down.";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.defaultstaticinterfacemethods.model;
|
||||
|
||||
public class MultiAlarmCar implements Vehicle, Alarm {
|
||||
|
||||
private final String brand;
|
||||
|
||||
public MultiAlarmCar(String brand) {
|
||||
this.brand = brand;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getBrand() {
|
||||
return brand;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String speedUp() {
|
||||
return "The motorbike is speeding up.";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String slowDown() {
|
||||
return "The mootorbike is slowing down.";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String turnAlarmOn() {
|
||||
return Vehicle.super.turnAlarmOn() + " " + Alarm.super.turnAlarmOn();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String turnAlarmOff() {
|
||||
return Vehicle.super.turnAlarmOff() + " " + Alarm.super.turnAlarmOff();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.defaultstaticinterfacemethods.model;
|
||||
|
||||
public interface Vehicle {
|
||||
|
||||
String getBrand();
|
||||
|
||||
String speedUp();
|
||||
|
||||
String slowDown();
|
||||
|
||||
default String turnAlarmOn() {
|
||||
return "Turning the vehice alarm on.";
|
||||
}
|
||||
|
||||
default String turnAlarmOff() {
|
||||
return "Turning the vehicle alarm off.";
|
||||
}
|
||||
|
||||
static int getHorsePower(int rpm, int torque) {
|
||||
return (rpm * torque) / 5252;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package com.baeldung.doublecolon;
|
||||
|
||||
public class Computer {
|
||||
|
||||
private Integer age;
|
||||
private String color;
|
||||
private Integer healty;
|
||||
|
||||
Computer(final int age, final String color) {
|
||||
this.age = age;
|
||||
this.color = color;
|
||||
}
|
||||
|
||||
Computer(final Integer age, final String color, final Integer healty) {
|
||||
this.age = age;
|
||||
this.color = color;
|
||||
this.healty = healty;
|
||||
}
|
||||
|
||||
public Computer() {
|
||||
}
|
||||
|
||||
public Integer getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(final Integer age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
String getColor() {
|
||||
return color;
|
||||
}
|
||||
|
||||
public void setColor(final String color) {
|
||||
this.color = color;
|
||||
}
|
||||
|
||||
Integer getHealty() {
|
||||
return healty;
|
||||
}
|
||||
|
||||
void setHealty(final Integer healty) {
|
||||
this.healty = healty;
|
||||
}
|
||||
|
||||
public void turnOnPc() {
|
||||
System.out.println("Computer turned on");
|
||||
}
|
||||
|
||||
public void turnOffPc() {
|
||||
System.out.println("Computer turned off");
|
||||
}
|
||||
|
||||
public Double calculateValue(Double initialValue) {
|
||||
return initialValue / 1.50;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Computer{" + "age=" + age + ", color='" + color + '\'' + ", healty=" + healty + '}';
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(final Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
final Computer computer = (Computer) o;
|
||||
|
||||
return (age != null ? age.equals(computer.age) : computer.age == null) && (color != null ? color.equals(computer.color) : computer.color == null);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = age != null ? age.hashCode() : 0;
|
||||
result = 31 * result + (color != null ? color.hashCode() : 0);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.doublecolon;
|
||||
|
||||
import com.baeldung.doublecolon.function.ComputerPredicate;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class ComputerUtils {
|
||||
|
||||
static final ComputerPredicate after2010Predicate = (c) -> (c.getAge() > 2010);
|
||||
static final ComputerPredicate blackPredicate = (c) -> "black".equals(c.getColor());
|
||||
|
||||
public static List<Computer> filter(final List<Computer> inventory, final ComputerPredicate p) {
|
||||
|
||||
final List<Computer> result = new ArrayList<>();
|
||||
inventory.stream().filter(p::filter).forEach(result::add);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
static void repair(final Computer computer) {
|
||||
if (computer.getHealty() < 50) {
|
||||
computer.setHealty(100);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.doublecolon;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.function.Function;
|
||||
|
||||
public class MacbookPro extends Computer {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(MacbookPro.class);
|
||||
|
||||
public MacbookPro(int age, String color) {
|
||||
super(age, color);
|
||||
}
|
||||
|
||||
MacbookPro(Integer age, String color, Integer healty) {
|
||||
super(age, color, healty);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void turnOnPc() {
|
||||
LOG.debug("MacbookPro turned on");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void turnOffPc() {
|
||||
LOG.debug("MacbookPro turned off");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Double calculateValue(Double initialValue) {
|
||||
|
||||
Function<Double, Double> function = super::calculateValue;
|
||||
final Double pcValue = function.apply(initialValue);
|
||||
LOG.debug("First value is:" + pcValue);
|
||||
return pcValue + (initialValue / 10);
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.doublecolon.function;
|
||||
|
||||
import com.baeldung.doublecolon.Computer;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface ComputerPredicate {
|
||||
|
||||
boolean filter(Computer c);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.doublecolon.function;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.function.Function;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface TriFunction<A, B, C, R> {
|
||||
|
||||
R apply(A a, B b, C c);
|
||||
|
||||
default <V> TriFunction<A, B, C, V> andThen(final Function<? super R, ? extends V> after) {
|
||||
Objects.requireNonNull(after);
|
||||
return (final A a, final B b, final C c) -> after.apply(apply(a, b, c));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.baeldung.java8.lambda.exceptions;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class LambdaExceptionWrappers {
|
||||
|
||||
public static Consumer<Integer> lambdaWrapper(Consumer<Integer> consumer) {
|
||||
return i -> {
|
||||
try {
|
||||
consumer.accept(i);
|
||||
} catch (ArithmeticException e) {
|
||||
System.err.println("Arithmetic Exception occured : " + e.getMessage());
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
static <T, E extends Exception> Consumer<T> consumerWrapper(Consumer<T> consumer, Class<E> clazz) {
|
||||
return i -> {
|
||||
try {
|
||||
consumer.accept(i);
|
||||
} catch (Exception ex) {
|
||||
try {
|
||||
E exCast = clazz.cast(ex);
|
||||
System.err.println("Exception occured : " + exCast.getMessage());
|
||||
} catch (ClassCastException ccEx) {
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public static <T> Consumer<T> throwingConsumerWrapper(ThrowingConsumer<T, Exception> throwingConsumer) {
|
||||
return i -> {
|
||||
try {
|
||||
throwingConsumer.accept(i);
|
||||
} catch (Exception ex) {
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public static <T, E extends Exception> Consumer<T> handlingConsumerWrapper(ThrowingConsumer<T, E> throwingConsumer, Class<E> exceptionClass) {
|
||||
return i -> {
|
||||
try {
|
||||
throwingConsumer.accept(i);
|
||||
} catch (Exception ex) {
|
||||
try {
|
||||
E exCast = exceptionClass.cast(ex);
|
||||
System.err.println("Exception occured : " + exCast.getMessage());
|
||||
} catch (ClassCastException ccEx) {
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.java8.lambda.exceptions;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface ThrowingConsumer<T, E extends Exception> {
|
||||
|
||||
void accept(T t) throws E;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.java8.lambda.tips;
|
||||
|
||||
|
||||
@FunctionalInterface
|
||||
public interface Bar {
|
||||
|
||||
String method(String string);
|
||||
|
||||
default String defaultMethod() {
|
||||
return "String from Bar";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.java8.lambda.tips;
|
||||
|
||||
|
||||
@FunctionalInterface
|
||||
public interface Baz {
|
||||
|
||||
String method(String string);
|
||||
|
||||
default String defaultMethod() {
|
||||
return "String from Baz";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.java8.lambda.tips;
|
||||
|
||||
|
||||
@FunctionalInterface
|
||||
public interface Foo {
|
||||
|
||||
String method(String string);
|
||||
|
||||
default void defaultMethod() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.java8.lambda.tips;
|
||||
|
||||
|
||||
@FunctionalInterface
|
||||
public interface FooExtended extends Baz, Bar {
|
||||
|
||||
@Override
|
||||
default String defaultMethod() {
|
||||
return Bar.super.defaultMethod();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.java8.lambda.tips;
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public interface Processor {
|
||||
|
||||
String processWithCallable(Callable<String> c) throws Exception;
|
||||
|
||||
String processWithSupplier(Supplier<String> s);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.java8.lambda.tips;
|
||||
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public class ProcessorImpl implements Processor {
|
||||
|
||||
@Override
|
||||
public String processWithCallable(Callable<String> c) throws Exception {
|
||||
return c.call();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String processWithSupplier(Supplier<String> s) {
|
||||
return s.get();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.java8.lambda.tips;
|
||||
|
||||
|
||||
import java.util.function.Function;
|
||||
|
||||
public class UseFoo {
|
||||
|
||||
private String value = "Enclosing scope value";
|
||||
|
||||
public String add(final String string, final Foo foo) {
|
||||
return foo.method(string);
|
||||
}
|
||||
|
||||
public String addWithStandardFI(final String string, final Function<String, String> fn) {
|
||||
return fn.apply(string);
|
||||
}
|
||||
|
||||
public String scopeExperiment() {
|
||||
final Foo fooIC = new Foo() {
|
||||
String value = "Inner class value";
|
||||
|
||||
@Override
|
||||
public String method(final String string) {
|
||||
return value;
|
||||
}
|
||||
};
|
||||
final String resultIC = fooIC.method("");
|
||||
|
||||
final Foo fooLambda = parameter -> {
|
||||
final String value = "Lambda value";
|
||||
return this.value;
|
||||
};
|
||||
final String resultLambda = fooLambda.method("");
|
||||
|
||||
return "Results: resultIC = " + resultIC + ", resultLambda = " + resultLambda;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.java_8_features;
|
||||
|
||||
public class Address {
|
||||
|
||||
private String street;
|
||||
|
||||
public String getStreet() {
|
||||
return street;
|
||||
}
|
||||
|
||||
public void setStreet(String street) {
|
||||
this.street = street;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package com.baeldung.java_8_features;
|
||||
|
||||
public class CustomException extends RuntimeException {
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.java_8_features;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public class OptionalAddress {
|
||||
|
||||
private String street;
|
||||
|
||||
public Optional<String> getStreet() {
|
||||
return Optional.ofNullable(street);
|
||||
}
|
||||
|
||||
public void setStreet(String street) {
|
||||
this.street = street;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.java_8_features;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public class OptionalUser {
|
||||
|
||||
private OptionalAddress address;
|
||||
|
||||
public Optional<OptionalAddress> getAddress() {
|
||||
return Optional.of(address);
|
||||
}
|
||||
|
||||
public void setAddress(OptionalAddress address) {
|
||||
this.address = address;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.baeldung.java_8_features;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public class User {
|
||||
|
||||
private String name;
|
||||
|
||||
private Address address;
|
||||
|
||||
public Address getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(Address address) {
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
public User() {
|
||||
}
|
||||
|
||||
public User(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public static boolean isRealUser(User user) {
|
||||
return true;
|
||||
}
|
||||
|
||||
public String getOrThrow() {
|
||||
String value = null;
|
||||
Optional<String> valueOpt = Optional.ofNullable(value);
|
||||
String result = valueOpt.orElseThrow(CustomException::new).toUpperCase();
|
||||
return result;
|
||||
}
|
||||
|
||||
public boolean isLegalName(String name) {
|
||||
return name.length() > 3 && name.length() < 16;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.java_8_features;
|
||||
|
||||
public interface Vehicle {
|
||||
|
||||
void moveTo(long altitude, long longitude);
|
||||
|
||||
static String producer() {
|
||||
return "N&F Vehicles";
|
||||
}
|
||||
|
||||
default long[] startPosition() {
|
||||
return new long[] { 23, 15 };
|
||||
}
|
||||
|
||||
default String getOverview() {
|
||||
return "ATV made by " + producer();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.java_8_features;
|
||||
|
||||
public class VehicleImpl implements Vehicle {
|
||||
|
||||
@Override
|
||||
public void moveTo(long altitude, long longitude) {
|
||||
// do nothing
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.java_8_features.groupingby;
|
||||
|
||||
public class BlogPost {
|
||||
private String title;
|
||||
private String author;
|
||||
private BlogPostType type;
|
||||
private int likes;
|
||||
|
||||
public BlogPost(String title, String author, BlogPostType type, int likes) {
|
||||
this.title = title;
|
||||
this.author = author;
|
||||
this.type = type;
|
||||
this.likes = likes;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public String getAuthor() {
|
||||
return author;
|
||||
}
|
||||
|
||||
public BlogPostType getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public int getLikes() {
|
||||
return likes;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "BlogPost{" + "title='" + title + '\'' + ", type=" + type + ", likes=" + likes + '}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.java_8_features.groupingby;
|
||||
|
||||
public enum BlogPostType {
|
||||
NEWS, REVIEW, GUIDE
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.nullsafecollectionstreams;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.stream.Stream;
|
||||
import static org.apache.commons.collections4.CollectionUtils.emptyIfNull;
|
||||
|
||||
public class NullSafeCollectionStreamsUsingCommonsEmptyIfNull {
|
||||
|
||||
/**
|
||||
* This method shows how to make a null safe stream from a collection through the use of
|
||||
* emptyIfNull() method from Apache Commons CollectionUtils library
|
||||
*
|
||||
* @param collection The collection that is to be converted into a stream
|
||||
* @return The stream that has been created from the collection or an empty stream if the collection is null
|
||||
*/
|
||||
public Stream<String> collectionAsStream(Collection<String> collection) {
|
||||
return emptyIfNull(collection).stream();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.nullsafecollectionstreams;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class NullSafeCollectionStreamsUsingJava8OptionalContainer {
|
||||
|
||||
/**
|
||||
* This method shows how to make a null safe stream from a collection through the use of
|
||||
* Java SE 8’s Optional Container
|
||||
*
|
||||
* @param collection The collection that is to be converted into a stream
|
||||
* @return The stream that has been created from the collection or an empty stream if the collection is null
|
||||
*/
|
||||
public Stream<String> collectionAsStream(Collection<String> collection) {
|
||||
return Optional.ofNullable(collection)
|
||||
.map(Collection::stream)
|
||||
.orElseGet(Stream::empty);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.nullsafecollectionstreams;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class NullSafeCollectionStreamsUsingNullDereferenceCheck {
|
||||
|
||||
/**
|
||||
* This method shows how to make a null safe stream from a collection through the use of a check
|
||||
* to prevent null dereferences
|
||||
*
|
||||
* @param collection The collection that is to be converted into a stream
|
||||
* @return The stream that has been created from the collection or an empty stream if the collection is null
|
||||
*/
|
||||
public Stream<String> collectionAsStream(Collection<String> collection) {
|
||||
return collection == null ? Stream.empty() : collection.stream();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.optional;
|
||||
|
||||
public class Modem {
|
||||
private Double price;
|
||||
|
||||
public Modem(Double price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public Double getPrice() {
|
||||
return price;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.optional;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Random;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class OrElseAndOrElseGet {
|
||||
|
||||
public static List<String> names = Arrays.asList("John", "Jones", "Kelly", "Cristina", "Raven");
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(OrElseAndOrElseGet.class);
|
||||
|
||||
public String getRandomName() {
|
||||
LOG.info("getRandomName() method - start");
|
||||
Random random = new Random();
|
||||
int index = random.nextInt(5);
|
||||
LOG.info("getRandomName() method - end");
|
||||
return names.get(index);
|
||||
}
|
||||
|
||||
public String getNameUsingOrElse(String name) {
|
||||
return Optional.ofNullable(name)
|
||||
.orElse(getRandomName());
|
||||
}
|
||||
|
||||
public String getNameUsingOrElseGet(String name) {
|
||||
return Optional.ofNullable(name)
|
||||
.orElseGet(() -> getRandomName());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.baeldung.optional;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.openjdk.jmh.annotations.Benchmark;
|
||||
import org.openjdk.jmh.annotations.BenchmarkMode;
|
||||
import org.openjdk.jmh.annotations.Fork;
|
||||
import org.openjdk.jmh.annotations.Mode;
|
||||
import org.openjdk.jmh.annotations.OutputTimeUnit;
|
||||
import org.openjdk.jmh.annotations.Scope;
|
||||
import org.openjdk.jmh.annotations.State;
|
||||
import org.openjdk.jmh.runner.RunnerException;
|
||||
|
||||
@Fork(1)
|
||||
@State(Scope.Benchmark)
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public class OrElseAndOrElseGetBenchmarkRunner {
|
||||
|
||||
private OrElseAndOrElseGet orElsevsOrElseGet = new OrElseAndOrElseGet();
|
||||
|
||||
public static void main(String[] args) throws RunnerException, IOException {
|
||||
org.openjdk.jmh.Main.main(args);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public String orElseBenchmark() {
|
||||
return orElsevsOrElseGet.getNameUsingOrElse("baeldung");
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public String orElseGetBenchmark() {
|
||||
return orElsevsOrElseGet.getNameUsingOrElseGet("baeldung");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.optional;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public class Person {
|
||||
private String name;
|
||||
private int age;
|
||||
private String password;
|
||||
|
||||
public Person(String name, int age) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public Optional<String> getName() {
|
||||
return Optional.ofNullable(name);
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Optional<Integer> getAge() {
|
||||
return Optional.ofNullable(age);
|
||||
}
|
||||
|
||||
public void setAge(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public Optional<String> getPassword() {
|
||||
return Optional.ofNullable(password);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.optional;
|
||||
|
||||
public class PersonRepository {
|
||||
|
||||
public String findNameById(String id) {
|
||||
return id == null ? null : "Name";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.primitive;
|
||||
|
||||
public class BenchmarkRunner {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
new IntPrimitiveLookup().run();
|
||||
new IntegerWrapperLookup().run();
|
||||
new FloatPrimitiveLookup().run();
|
||||
new FloatWrapperLookup().run();
|
||||
new DoublePrimitiveLookup().run();
|
||||
new DoubleWrapperLookup().run();
|
||||
new ShortPrimitiveLookup().run();
|
||||
new ShortWrapperLookup().run();
|
||||
new BooleanPrimitiveLookup().run();
|
||||
new BooleanWrapperLookup().run();
|
||||
new CharPrimitiveLookup().run();
|
||||
new CharacterWrapperLookup().run();
|
||||
new BytePrimitiveLookup().run();
|
||||
new ByteWrapperLookup().run();
|
||||
new LongPrimitiveLookup().run();
|
||||
new LongWrapperLookup().run();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.primitive;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
@State(Scope.Thread)
|
||||
public class BooleanPrimitiveLookup extends Lookup {
|
||||
|
||||
private boolean[] elements;
|
||||
private final boolean pivot = false;
|
||||
|
||||
@Setup
|
||||
@Override
|
||||
public void prepare() {
|
||||
elements = new boolean[s];
|
||||
for (int i = 0; i < s - 1; i++) {
|
||||
elements[i] = true;
|
||||
}
|
||||
elements[s - 1] = pivot;
|
||||
}
|
||||
|
||||
@TearDown
|
||||
@Override
|
||||
public void clean() {
|
||||
elements = null;
|
||||
}
|
||||
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
public int findPosition() {
|
||||
int index = 0;
|
||||
while (pivot != elements[index]) {
|
||||
index++;
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSimpleClassName() {
|
||||
return BooleanPrimitiveLookup.class.getSimpleName();
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.primitive;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
@State(Scope.Thread)
|
||||
public class BooleanWrapperLookup extends Lookup {
|
||||
private Boolean[] elements;
|
||||
private final boolean pivot = false;
|
||||
|
||||
@Override
|
||||
@Setup
|
||||
public void prepare() {
|
||||
elements = new Boolean[s];
|
||||
for (int i = 0; i < s - 1; i++) {
|
||||
elements[i] = true;
|
||||
}
|
||||
elements[s - 1] = pivot;
|
||||
}
|
||||
|
||||
@Override
|
||||
@TearDown
|
||||
public void clean() {
|
||||
elements = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
public int findPosition() {
|
||||
int index = 0;
|
||||
Boolean pivotWrapper = pivot;
|
||||
while (!pivotWrapper.equals(elements[index])) {
|
||||
index++;
|
||||
}
|
||||
return index;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSimpleClassName() {
|
||||
return BooleanWrapperLookup.class.getSimpleName();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.baeldung.primitive;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
@State(Scope.Thread)
|
||||
public class BytePrimitiveLookup extends Lookup {
|
||||
|
||||
private byte[] elements;
|
||||
private final byte pivot = 2;
|
||||
|
||||
@Setup
|
||||
@Override
|
||||
public void prepare() {
|
||||
byte common = 1;
|
||||
elements = new byte[s];
|
||||
for (int i = 0; i < s - 1; i++) {
|
||||
elements[i] = common;
|
||||
}
|
||||
elements[s - 1] = pivot;
|
||||
}
|
||||
|
||||
@TearDown
|
||||
@Override
|
||||
public void clean() {
|
||||
elements = null;
|
||||
}
|
||||
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
public int findPosition() {
|
||||
int index = 0;
|
||||
while (pivot != elements[index]) {
|
||||
index++;
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSimpleClassName() {
|
||||
return BytePrimitiveLookup.class.getSimpleName();
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.baeldung.primitive;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
@State(Scope.Thread)
|
||||
public class ByteWrapperLookup extends Lookup {
|
||||
private Byte[] elements;
|
||||
private final byte pivot = 2;
|
||||
|
||||
@Override
|
||||
@Setup
|
||||
public void prepare() {
|
||||
byte common = 1;
|
||||
elements = new Byte[s];
|
||||
for (int i = 0; i < s - 1; i++) {
|
||||
elements[i] = common;
|
||||
}
|
||||
elements[s - 1] = pivot;
|
||||
}
|
||||
|
||||
@Override
|
||||
@TearDown
|
||||
public void clean() {
|
||||
elements = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
public int findPosition() {
|
||||
int index = 0;
|
||||
Byte pivotWrapper = pivot;
|
||||
while (!pivotWrapper.equals(elements[index])) {
|
||||
index++;
|
||||
}
|
||||
return index;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSimpleClassName() {
|
||||
return ByteWrapperLookup.class.getSimpleName();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.baeldung.primitive;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
@State(Scope.Thread)
|
||||
public class CharPrimitiveLookup extends Lookup {
|
||||
|
||||
private char[] elements;
|
||||
private final char pivot = 'b';
|
||||
|
||||
@Setup
|
||||
@Override
|
||||
public void prepare() {
|
||||
char common = 'a';
|
||||
elements = new char[s];
|
||||
for (int i = 0; i < s - 1; i++) {
|
||||
elements[i] = common;
|
||||
}
|
||||
elements[s - 1] = pivot;
|
||||
}
|
||||
|
||||
@TearDown
|
||||
@Override
|
||||
public void clean() {
|
||||
elements = null;
|
||||
}
|
||||
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
public int findPosition() {
|
||||
int index = 0;
|
||||
while (pivot != elements[index]) {
|
||||
index++;
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSimpleClassName() {
|
||||
return CharPrimitiveLookup.class.getSimpleName();
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.baeldung.primitive;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
@State(Scope.Thread)
|
||||
public class CharacterWrapperLookup extends Lookup {
|
||||
private Character[] elements;
|
||||
private final char pivot = 'b';
|
||||
|
||||
@Override
|
||||
@Setup
|
||||
public void prepare() {
|
||||
char common = 'a';
|
||||
elements = new Character[s];
|
||||
for (int i = 0; i < s - 1; i++) {
|
||||
elements[i] = common;
|
||||
}
|
||||
elements[s - 1] = pivot;
|
||||
}
|
||||
|
||||
@Override
|
||||
@TearDown
|
||||
public void clean() {
|
||||
elements = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
public int findPosition() {
|
||||
int index = 0;
|
||||
Character pivotWrapper = pivot;
|
||||
while (!pivotWrapper.equals(elements[index])) {
|
||||
index++;
|
||||
}
|
||||
return index;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSimpleClassName() {
|
||||
return CharacterWrapperLookup.class.getSimpleName();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.baeldung.primitive;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
@State(Scope.Thread)
|
||||
public class DoublePrimitiveLookup extends Lookup {
|
||||
private double[] elements;
|
||||
private final double pivot = 2;
|
||||
|
||||
@Setup
|
||||
@Override
|
||||
public void prepare() {
|
||||
double common = 1;
|
||||
elements = new double[s];
|
||||
for (int i = 0; i < s - 1; i++) {
|
||||
elements[i] = common;
|
||||
}
|
||||
elements[s - 1] = pivot;
|
||||
}
|
||||
|
||||
@TearDown
|
||||
@Override
|
||||
public void clean() {
|
||||
elements = null;
|
||||
}
|
||||
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
public int findPosition() {
|
||||
int index = 0;
|
||||
while (pivot != elements[index]) {
|
||||
index++;
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSimpleClassName() {
|
||||
return DoublePrimitiveLookup.class.getSimpleName();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.primitive;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
@State(Scope.Thread)
|
||||
public class DoubleWrapperLookup extends Lookup {
|
||||
private Double[] elements;
|
||||
private final double pivot = 2d;
|
||||
|
||||
@Override
|
||||
@Setup
|
||||
public void prepare() {
|
||||
double common = 1;
|
||||
elements = new Double[s];
|
||||
for (int i = 0; i < s - 1; i++) {
|
||||
elements[i] = common;
|
||||
}
|
||||
elements[s - 1] = pivot;
|
||||
}
|
||||
|
||||
@Override
|
||||
@TearDown
|
||||
public void clean() {
|
||||
elements = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
public int findPosition() {
|
||||
int index = 0;
|
||||
Double pivotWrapper = pivot;
|
||||
while (!pivotWrapper.equals(elements[index])) {
|
||||
index++;
|
||||
}
|
||||
return index;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSimpleClassName() {
|
||||
return DoubleWrapperLookup.class.getSimpleName();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.baeldung.primitive;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
@State(Scope.Thread)
|
||||
public class FloatPrimitiveLookup extends Lookup {
|
||||
private float[] elements;
|
||||
private final float pivot = 2;
|
||||
|
||||
@Setup
|
||||
@Override
|
||||
public void prepare() {
|
||||
int common = 1;
|
||||
elements = new float[s];
|
||||
for (int i = 0; i < s - 1; i++) {
|
||||
elements[i] = common;
|
||||
}
|
||||
elements[s - 1] = pivot;
|
||||
}
|
||||
|
||||
@TearDown
|
||||
@Override
|
||||
public void clean() {
|
||||
elements = null;
|
||||
}
|
||||
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
public int findPosition() {
|
||||
int index = 0;
|
||||
while (pivot != elements[index]) {
|
||||
index++;
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSimpleClassName() {
|
||||
return FloatPrimitiveLookup.class.getSimpleName();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.primitive;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
@State(Scope.Thread)
|
||||
public class FloatWrapperLookup extends Lookup {
|
||||
private Float[] elements;
|
||||
private final float pivot = 2;
|
||||
|
||||
@Override
|
||||
@Setup
|
||||
public void prepare() {
|
||||
float common = 1;
|
||||
elements = new Float[s];
|
||||
for (int i = 0; i < s - 1; i++) {
|
||||
elements[i] = common;
|
||||
}
|
||||
elements[s - 1] = pivot;
|
||||
}
|
||||
|
||||
@Override
|
||||
@TearDown
|
||||
public void clean() {
|
||||
elements = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
public int findPosition() {
|
||||
int index = 0;
|
||||
Float pivotWrapper = pivot;
|
||||
while (!pivotWrapper.equals(elements[index])) {
|
||||
index++;
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSimpleClassName() {
|
||||
return FloatWrapperLookup.class.getSimpleName();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.primitive;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
@State(Scope.Thread)
|
||||
public class IntPrimitiveLookup extends Lookup {
|
||||
|
||||
private int[] elements;
|
||||
private final int pivot = 2;
|
||||
|
||||
@Setup
|
||||
@Override
|
||||
public void prepare() {
|
||||
int common = 1;
|
||||
elements = new int[s];
|
||||
for (int i = 0; i < s - 1; i++) {
|
||||
elements[i] = common;
|
||||
}
|
||||
elements[s - 1] = pivot;
|
||||
}
|
||||
|
||||
@TearDown
|
||||
@Override
|
||||
public void clean() {
|
||||
elements = null;
|
||||
}
|
||||
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
public int findPosition() {
|
||||
int index = 0;
|
||||
while (pivot != elements[index]) {
|
||||
index++;
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSimpleClassName() {
|
||||
return IntPrimitiveLookup.class.getSimpleName();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.primitive;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
@State(Scope.Thread)
|
||||
public class IntegerWrapperLookup extends Lookup {
|
||||
private Integer[] elements;
|
||||
private final int pivot = 2;
|
||||
|
||||
@Override
|
||||
@Setup
|
||||
public void prepare() {
|
||||
int common = 1;
|
||||
elements = new Integer[s];
|
||||
for (int i = 0; i < s - 1; i++) {
|
||||
elements[i] = common;
|
||||
}
|
||||
elements[s - 1] = pivot;
|
||||
}
|
||||
|
||||
@Override
|
||||
@TearDown
|
||||
public void clean() {
|
||||
elements = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
public int findPosition() {
|
||||
int index = 0;
|
||||
Integer pivotWrapper = pivot;
|
||||
while (!pivotWrapper.equals(elements[index])) {
|
||||
index++;
|
||||
}
|
||||
return index;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSimpleClassName() {
|
||||
return IntegerWrapperLookup.class.getSimpleName();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.baeldung.primitive;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
@State(Scope.Thread)
|
||||
public class LongPrimitiveLookup extends Lookup {
|
||||
private long[] elements;
|
||||
private final long pivot = 2;
|
||||
|
||||
@Setup
|
||||
@Override
|
||||
public void prepare() {
|
||||
long common = 1;
|
||||
elements = new long[s];
|
||||
for (int i = 0; i < s - 1; i++) {
|
||||
elements[i] = common;
|
||||
}
|
||||
elements[s - 1] = pivot;
|
||||
}
|
||||
|
||||
@TearDown
|
||||
@Override
|
||||
public void clean() {
|
||||
elements = null;
|
||||
}
|
||||
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
public int findPosition() {
|
||||
int index = 0;
|
||||
while (pivot != elements[index]) {
|
||||
index++;
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSimpleClassName() {
|
||||
return LongPrimitiveLookup.class.getSimpleName();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.primitive;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
@State(Scope.Thread)
|
||||
public class LongWrapperLookup extends Lookup{
|
||||
private Long[] elements;
|
||||
private final long pivot = 2;
|
||||
|
||||
@Override
|
||||
@Setup
|
||||
public void prepare() {
|
||||
long common = 1;
|
||||
elements = new Long[s];
|
||||
for (int i = 0; i < s - 1; i++) {
|
||||
elements[i] = common;
|
||||
}
|
||||
elements[s - 1] = pivot;
|
||||
}
|
||||
|
||||
@Override
|
||||
@TearDown
|
||||
public void clean() {
|
||||
elements = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
public int findPosition() {
|
||||
int index = 0;
|
||||
Long pivotWrapper = pivot;
|
||||
while (!pivotWrapper.equals(elements[index])) {
|
||||
index++;
|
||||
}
|
||||
return index;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSimpleClassName() {
|
||||
return LongWrapperLookup.class.getSimpleName();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.baeldung.primitive;
|
||||
|
||||
import org.openjdk.jmh.results.RunResult;
|
||||
import org.openjdk.jmh.runner.Runner;
|
||||
import org.openjdk.jmh.runner.RunnerException;
|
||||
import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
/**
|
||||
* An abstract class that is to be extended by the classes that
|
||||
* perform lookup in the arrays either of Java primitive types or their wrappers.
|
||||
*/
|
||||
public abstract class Lookup {
|
||||
/**
|
||||
* the array size
|
||||
*/
|
||||
final protected int s = 50000000;
|
||||
|
||||
/**
|
||||
* Initialize the array: fill in the array with the same
|
||||
* elements except for the last one.
|
||||
*/
|
||||
abstract public void prepare();
|
||||
|
||||
/**
|
||||
* Free the array's reference.
|
||||
*/
|
||||
abstract public void clean();
|
||||
|
||||
/**
|
||||
* Find the position of the element that is different from the others.
|
||||
* By construction, it is the last array element.
|
||||
*
|
||||
* @return array's last element index
|
||||
*/
|
||||
abstract public int findPosition();
|
||||
|
||||
/**
|
||||
* Get the name of the class that extends this one. It is needed in order
|
||||
* to set up the benchmark.
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
abstract public String getSimpleClassName();
|
||||
|
||||
Collection<RunResult> run() throws RunnerException {
|
||||
Options opt = new OptionsBuilder()
|
||||
.include(getSimpleClassName())
|
||||
.forks(1)
|
||||
.build();
|
||||
return new Runner(opt).run();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.primitive;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
@State(Scope.Thread)
|
||||
public class ShortPrimitiveLookup extends Lookup {
|
||||
|
||||
private short[] elements;
|
||||
private final short pivot = 2;
|
||||
|
||||
@Setup
|
||||
@Override
|
||||
public void prepare() {
|
||||
short common = 1;
|
||||
elements = new short[s];
|
||||
for (int i = 0; i < s - 1; i++) {
|
||||
elements[i] = common;
|
||||
}
|
||||
elements[s - 1] = pivot;
|
||||
}
|
||||
|
||||
@TearDown
|
||||
@Override
|
||||
public void clean() {
|
||||
elements = null;
|
||||
}
|
||||
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
public int findPosition() {
|
||||
int index = 0;
|
||||
while (pivot != elements[index]) {
|
||||
index++;
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSimpleClassName() {
|
||||
return ShortPrimitiveLookup.class.getSimpleName();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.baeldung.primitive;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
@State(Scope.Thread)
|
||||
public class ShortWrapperLookup extends Lookup {
|
||||
private Short[] elements;
|
||||
private final short pivot = 2;
|
||||
|
||||
@Override
|
||||
@Setup
|
||||
public void prepare() {
|
||||
short common = 1;
|
||||
elements = new Short[s];
|
||||
for (int i = 0; i < s - 1; i++) {
|
||||
elements[i] = common;
|
||||
}
|
||||
elements[s - 1] = pivot;
|
||||
}
|
||||
|
||||
@Override
|
||||
@TearDown
|
||||
public void clean() {
|
||||
elements = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
public int findPosition() {
|
||||
int index = 0;
|
||||
Short pivotWrapper = pivot;
|
||||
while (!pivotWrapper.equals(elements[index])) {
|
||||
index++;
|
||||
}
|
||||
return index;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSimpleClassName() {
|
||||
return ShortWrapperLookup.class.getSimpleName();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -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,18 @@
|
||||
package com.baeldung.reflect;
|
||||
|
||||
public class Person {
|
||||
|
||||
private String fullName;
|
||||
|
||||
public Person(String fullName) {
|
||||
this.fullName = fullName;
|
||||
}
|
||||
|
||||
public void setFullName(String fullName) {
|
||||
this.fullName = fullName;
|
||||
}
|
||||
|
||||
public String getFullName() {
|
||||
return fullName;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.spliteratorAPI;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class Article {
|
||||
private List<Author> listOfAuthors;
|
||||
private int id;
|
||||
private String name;
|
||||
|
||||
public Article(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Article(List<Author> listOfAuthors, int id) {
|
||||
super();
|
||||
this.listOfAuthors = listOfAuthors;
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public List<Author> getListOfAuthors() {
|
||||
return listOfAuthors;
|
||||
}
|
||||
|
||||
public void setListOfAuthors(List<Author> listOfAuthors) {
|
||||
this.listOfAuthors = listOfAuthors;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.baeldung.spliteratorAPI;
|
||||
|
||||
public class Author {
|
||||
private String name;
|
||||
private int relatedArticleId;
|
||||
|
||||
public Author(String name, int relatedArticleId) {
|
||||
this.name = name;
|
||||
this.relatedArticleId = relatedArticleId;
|
||||
}
|
||||
|
||||
public int getRelatedArticleId() {
|
||||
return relatedArticleId;
|
||||
}
|
||||
|
||||
public void setRelatedArticleId(int relatedArticleId) {
|
||||
this.relatedArticleId = relatedArticleId;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "[name: " + name + ", relatedId: " + relatedArticleId + "]";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.spliteratorAPI;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class Executor {
|
||||
|
||||
public static int countAutors(Stream<Author> stream) {
|
||||
RelatedAuthorCounter wordCounter = stream.reduce(new RelatedAuthorCounter(0, true),
|
||||
RelatedAuthorCounter::accumulate, RelatedAuthorCounter::combine);
|
||||
return wordCounter.getCounter();
|
||||
}
|
||||
|
||||
public static List<Article> generateElements() {
|
||||
return Stream.generate(() -> new Article("Java")).limit(35000).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.spliteratorAPI;
|
||||
|
||||
public class RelatedAuthorCounter {
|
||||
private final int counter;
|
||||
private final boolean isRelated;
|
||||
|
||||
public RelatedAuthorCounter(int counter, boolean isRelated) {
|
||||
this.counter = counter;
|
||||
this.isRelated = isRelated;
|
||||
}
|
||||
|
||||
public RelatedAuthorCounter accumulate(Author author) {
|
||||
if (author.getRelatedArticleId() == 0) {
|
||||
return isRelated ? this : new RelatedAuthorCounter(counter, true);
|
||||
} else {
|
||||
return isRelated ? new RelatedAuthorCounter(counter + 1, false) : this;
|
||||
}
|
||||
}
|
||||
|
||||
public RelatedAuthorCounter combine(RelatedAuthorCounter RelatedAuthorCounter) {
|
||||
return new RelatedAuthorCounter(counter + RelatedAuthorCounter.counter, RelatedAuthorCounter.isRelated);
|
||||
}
|
||||
|
||||
public int getCounter() {
|
||||
return counter;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.baeldung.spliteratorAPI;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Spliterator;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class RelatedAuthorSpliterator implements Spliterator<Author> {
|
||||
private final List<Author> list;
|
||||
AtomicInteger current = new AtomicInteger();
|
||||
|
||||
public RelatedAuthorSpliterator(List<Author> list) {
|
||||
this.list = list;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean tryAdvance(Consumer<? super Author> action) {
|
||||
|
||||
action.accept(list.get(current.getAndIncrement()));
|
||||
return current.get() < list.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Spliterator<Author> trySplit() {
|
||||
int currentSize = list.size() - current.get();
|
||||
if (currentSize < 10) {
|
||||
return null;
|
||||
}
|
||||
for (int splitPos = currentSize / 2 + current.intValue(); splitPos < list.size(); splitPos++) {
|
||||
if (list.get(splitPos).getRelatedArticleId() == 0) {
|
||||
Spliterator<Author> spliterator = new RelatedAuthorSpliterator(list.subList(current.get(), splitPos));
|
||||
current.set(splitPos);
|
||||
return spliterator;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long estimateSize() {
|
||||
return list.size() - current.get();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int characteristics() {
|
||||
return CONCURRENT;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.spliteratorAPI;
|
||||
|
||||
import java.util.Spliterator;
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
public class Task implements Callable<String> {
|
||||
private Spliterator<Article> spliterator;
|
||||
private final static String SUFFIX = "- published by Baeldung";
|
||||
|
||||
public Task(Spliterator<Article> spliterator) {
|
||||
this.spliterator = spliterator;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String call() {
|
||||
int current = 0;
|
||||
while (spliterator.tryAdvance(article -> {
|
||||
article.setName(article.getName()
|
||||
.concat(SUFFIX));
|
||||
})) {
|
||||
current++;
|
||||
}
|
||||
;
|
||||
return Thread.currentThread()
|
||||
.getName() + ":" + current;
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user