[BAEL-13506] - Split or move core-java-8 module (#7790)

This commit is contained in:
Amit Pandey
2019-09-20 19:00:34 +05:30
committed by Josh Cummings
parent 7d65b1fb24
commit f2cac1ab7c
124 changed files with 640 additions and 51 deletions

View File

@@ -3,35 +3,12 @@
## Core Java 8 Cookbooks and Examples
### Relevant Articles:
- [Guide to Java 8s Collectors](http://www.baeldung.com/java-8-collectors)
- [New Features in Java 8](http://www.baeldung.com/java-8-new-features)
- [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)
- [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)
- [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)
- [Creating a Custom Annotation in Java](https://www.baeldung.com/java-custom-annotation)
- [The Difference Between Collection.stream().forEach() and Collection.forEach()](https://www.baeldung.com/java-collection-stream-foreach)
- [New Features in Java 8](https://www.baeldung.com/java-8-new-features)
- [Guide to Java 8 groupingBy Collector](https://www.baeldung.com/java-groupingby-collector)
- [Strategy Design Pattern in Java 8](https://www.baeldung.com/java-strategy-pattern)
- [Guide to Java 8 Comparator.comparing()](https://www.baeldung.com/java-8-comparator-comparing)
- [Guide to the Java 8 forEach](https://www.baeldung.com/foreach-java)
- [Introduction to Spliterator in Java](https://www.baeldung.com/java-spliterator)
- [Finding Min/Max in an Array with Java](https://www.baeldung.com/java-array-min-max)
- [Internationalization and Localization in Java 8](https://www.baeldung.com/java-8-localization)
- [Generalized Target-Type Inference in Java](https://www.baeldung.com/java-generalized-target-type-inference)

View File

@@ -116,12 +116,6 @@
<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>
@@ -150,16 +144,6 @@
</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>
@@ -176,7 +160,6 @@
<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>

View File

@@ -1,5 +0,0 @@
package com.baeldung.annotations;
@Deprecated
class ClassWithAnnotation {
}

View File

@@ -1,9 +0,0 @@
package com.baeldung.annotations;
class ClassWithDeprecatedMethod {
@Deprecated
static void deprecatedMethod() {
}
}

View File

@@ -1,11 +0,0 @@
package com.baeldung.annotations;
class ClassWithSafeVarargs<T> {
@SafeVarargs
final void iterateOverVarargs(T... args) {
for (T x : args) {
// do stuff with x
}
}
}

View File

@@ -1,9 +0,0 @@
package com.baeldung.annotations;
class ClassWithSuppressWarnings {
@SuppressWarnings("deprecation")
void useDeprecatedMethod() {
ClassWithDeprecatedMethod.deprecatedMethod(); // no warning is generated here
}
}

View File

@@ -1,8 +0,0 @@
package com.baeldung.annotations;
@FunctionalInterface
interface IntConsumer {
void accept(Integer number);
}

View File

@@ -1,8 +0,0 @@
package com.baeldung.annotations;
import java.lang.annotation.Repeatable;
@Repeatable(Intervals.class)
@interface Interval {
int hour() default 1;
}

View File

@@ -1,9 +0,0 @@
package com.baeldung.annotations;
public class IntervalUsage {
@Interval(hour = 17)
@Interval(hour = 13)
void doPeriodicCleanup() {
}
}

View File

@@ -1,5 +0,0 @@
package com.baeldung.annotations;
@interface Intervals {
Interval[] value();
}

View File

@@ -1,11 +0,0 @@
package com.baeldung.annotations;
import java.lang.annotation.*;
@Inherited
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.LOCAL_VARIABLE, ElementType.FIELD})
@interface MyAnnotation {
}

View File

@@ -1,16 +0,0 @@
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;
}
}

View File

@@ -1,6 +0,0 @@
package com.baeldung.annotations;
interface MyOperation {
void perform();
}

View File

@@ -1,9 +0,0 @@
package com.baeldung.annotations;
class MyOperationImpl implements MyOperation {
@Override
public void perform() {
}
}

View File

@@ -1,13 +0,0 @@
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 {
}

View File

@@ -1,13 +0,0 @@
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 "";
}

View File

@@ -1,13 +0,0 @@
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 {
}

View File

@@ -1,10 +0,0 @@
package com.baeldung.customannotations;
public class JsonSerializationException extends RuntimeException {
private static final long serialVersionUID = 1L;
public JsonSerializationException(String message) {
super(message);
}
}

View File

@@ -1,67 +0,0 @@
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;
}
}

View File

@@ -1,66 +0,0 @@
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;
}
}

View File

@@ -1,18 +0,0 @@
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));
}
}

View File

@@ -1,12 +0,0 @@
package com.baeldung.defaultstaticinterfacemethods.model;
public interface Alarm {
default String turnAlarmOn() {
return "Turning the alarm on.";
}
default String turnAlarmOff() {
return "Turning the alarm off.";
}
}

View File

@@ -1,25 +0,0 @@
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.";
}
}

View File

@@ -1,25 +0,0 @@
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.";
}
}

View File

@@ -1,35 +0,0 @@
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();
}
}

View File

@@ -1,22 +0,0 @@
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;
}
}

View File

@@ -1,85 +0,0 @@
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;
}
}

View File

@@ -1,27 +0,0 @@
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);
}
}
}

View File

@@ -1,39 +0,0 @@
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);
}
}

View File

@@ -1,10 +0,0 @@
package com.baeldung.doublecolon.function;
import com.baeldung.doublecolon.Computer;
@FunctionalInterface
public interface ComputerPredicate {
boolean filter(Computer c);
}

View File

@@ -1,15 +0,0 @@
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));
}
}

View File

@@ -1,13 +0,0 @@
package com.baeldung.optional;
public class Modem {
private Double price;
public Modem(Double price) {
this.price = price;
}
public Double getPrice() {
return price;
}
}

View File

@@ -1,34 +0,0 @@
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());
}
}

View File

@@ -1,37 +0,0 @@
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");
}
}

View File

@@ -1,39 +0,0 @@
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);
}
}

View File

@@ -1,23 +0,0 @@
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();
}
}

View File

@@ -1,45 +0,0 @@
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();
}
}

View File

@@ -1,45 +0,0 @@
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();
}
}

View File

@@ -1,46 +0,0 @@
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();
}
}

View File

@@ -1,46 +0,0 @@
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();
}
}

View File

@@ -1,46 +0,0 @@
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();
}
}

View File

@@ -1,46 +0,0 @@
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();
}
}

View File

@@ -1,42 +0,0 @@
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();
}
}

View File

@@ -1,45 +0,0 @@
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();
}
}

View File

@@ -1,42 +0,0 @@
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();
}
}

View File

@@ -1,43 +0,0 @@
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();
}
}

View File

@@ -1,45 +0,0 @@
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();
}
}

View File

@@ -1,45 +0,0 @@
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();
}
}

View File

@@ -1,42 +0,0 @@
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();
}
}

View File

@@ -1,45 +0,0 @@
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();
}
}

View File

@@ -1,56 +0,0 @@
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();
}
}

View File

@@ -1,45 +0,0 @@
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();
}
}

View File

@@ -1,46 +0,0 @@
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();
}
}

View File

@@ -1,17 +0,0 @@
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;
}
}

View File

@@ -1,21 +0,0 @@
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);
}
}

View File

@@ -1,8 +0,0 @@
package com.baeldung.reducingIfElse;
public class Addition implements Operation {
@Override
public int apply(int a, int b) {
return a + b;
}
}

View File

@@ -1,83 +0,0 @@
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();
}
}

View File

@@ -1,5 +0,0 @@
package com.baeldung.reducingIfElse;
public interface Command {
Integer execute();
}

View File

@@ -1,7 +0,0 @@
package com.baeldung.reducingIfElse;
public class Division implements Operation {
@Override public int apply(int a, int b) {
return a / b;
}
}

View File

@@ -1,26 +0,0 @@
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;
}
}

View File

@@ -1,7 +0,0 @@
package com.baeldung.reducingIfElse;
public class Modulo implements Operation {
@Override public int apply(int a, int b) {
return a % b;
}
}

View File

@@ -1,7 +0,0 @@
package com.baeldung.reducingIfElse;
public class Multiplication implements Operation {
@Override public int apply(int a, int b) {
return 0;
}
}

View File

@@ -1,5 +0,0 @@
package com.baeldung.reducingIfElse;
public interface Operation {
int apply(int a, int b);
}

View File

@@ -1,41 +0,0 @@
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);
}

View File

@@ -1,21 +0,0 @@
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));
}
}

View File

@@ -1,13 +0,0 @@
package com.baeldung.reducingIfElse;
public class Result {
int value;
public Result(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}

View File

@@ -1,8 +0,0 @@
package com.baeldung.reducingIfElse;
public interface Rule {
boolean evaluate(Expression expression);
Result getResult();
}

View File

@@ -1,24 +0,0 @@
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();
}
}

View File

@@ -1,7 +0,0 @@
package com.baeldung.reducingIfElse;
public class Subtraction implements Operation {
@Override public int apply(int a, int b) {
return a - b;
}
}

View File

@@ -1,231 +0,0 @@
package com.baeldung.collectors;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import org.junit.Test;
import java.util.Arrays;
import java.util.Comparator;
import java.util.DoubleSummaryStatistics;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
import static com.google.common.collect.Sets.newHashSet;
import static java.util.stream.Collectors.averagingDouble;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.counting;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.maxBy;
import static java.util.stream.Collectors.partitioningBy;
import static java.util.stream.Collectors.summarizingDouble;
import static java.util.stream.Collectors.summingDouble;
import static java.util.stream.Collectors.toCollection;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
import static java.util.stream.Collectors.toSet;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class Java8CollectorsUnitTest {
private final List<String> givenList = Arrays.asList("a", "bb", "ccc", "dd");
private final List<String> listWithDuplicates = Arrays.asList("a", "bb", "c", "d", "bb");
@Test
public void whenCollectingToList_shouldCollectToList() throws Exception {
final List<String> result = givenList.stream().collect(toList());
assertThat(result).containsAll(givenList);
}
@Test
public void whenCollectingToSet_shouldCollectToSet() throws Exception {
final Set<String> result = givenList.stream().collect(toSet());
assertThat(result).containsAll(givenList);
}
@Test
public void givenContainsDuplicateElements_whenCollectingToSet_shouldAddDuplicateElementsOnlyOnce() throws Exception {
final Set<String> result = listWithDuplicates.stream().collect(toSet());
assertThat(result).hasSize(4);
}
@Test
public void whenCollectingToCollection_shouldCollectToCollection() throws Exception {
final List<String> result = givenList.stream().collect(toCollection(LinkedList::new));
assertThat(result).containsAll(givenList).isInstanceOf(LinkedList.class);
}
@Test
public void whenCollectingToImmutableCollection_shouldThrowException() throws Exception {
assertThatThrownBy(() -> {
givenList.stream().collect(toCollection(ImmutableList::of));
}).isInstanceOf(UnsupportedOperationException.class);
}
@Test
public void whenCollectingToMap_shouldCollectToMap() throws Exception {
final Map<String, Integer> result = givenList.stream().collect(toMap(Function.identity(), String::length));
assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2);
}
@Test
public void whenCollectingToMapwWithDuplicates_shouldCollectToMapMergingTheIdenticalItems() throws Exception {
final Map<String, Integer> result = listWithDuplicates.stream().collect(
toMap(
Function.identity(),
String::length,
(item, identicalItem) -> item
)
);
assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("c", 1).containsEntry("d", 1);
}
@Test
public void givenContainsDuplicateElements_whenCollectingToMap_shouldThrowException() throws Exception {
assertThatThrownBy(() -> {
listWithDuplicates.stream().collect(toMap(Function.identity(), String::length));
}).isInstanceOf(IllegalStateException.class);
}
@Test
public void whenCollectingAndThen_shouldCollect() throws Exception {
final List<String> result = givenList.stream().collect(collectingAndThen(toList(), ImmutableList::copyOf));
assertThat(result).containsAll(givenList).isInstanceOf(ImmutableList.class);
}
@Test
public void whenJoining_shouldJoin() throws Exception {
final String result = givenList.stream().collect(joining());
assertThat(result).isEqualTo("abbcccdd");
}
@Test
public void whenJoiningWithSeparator_shouldJoinWithSeparator() throws Exception {
final String result = givenList.stream().collect(joining(" "));
assertThat(result).isEqualTo("a bb ccc dd");
}
@Test
public void whenJoiningWithSeparatorAndPrefixAndPostfix_shouldJoinWithSeparatorPrePost() throws Exception {
final String result = givenList.stream().collect(joining(" ", "PRE-", "-POST"));
assertThat(result).isEqualTo("PRE-a bb ccc dd-POST");
}
@Test
public void whenPartitioningBy_shouldPartition() throws Exception {
final Map<Boolean, List<String>> result = givenList.stream().collect(partitioningBy(s -> s.length() > 2));
assertThat(result).containsKeys(true, false).satisfies(booleanListMap -> {
assertThat(booleanListMap.get(true)).contains("ccc");
assertThat(booleanListMap.get(false)).contains("a", "bb", "dd");
});
}
@Test
public void whenCounting_shouldCount() throws Exception {
final Long result = givenList.stream().collect(counting());
assertThat(result).isEqualTo(4);
}
@Test
public void whenSummarizing_shouldSummarize() throws Exception {
final DoubleSummaryStatistics result = givenList.stream().collect(summarizingDouble(String::length));
assertThat(result.getAverage()).isEqualTo(2);
assertThat(result.getCount()).isEqualTo(4);
assertThat(result.getMax()).isEqualTo(3);
assertThat(result.getMin()).isEqualTo(1);
assertThat(result.getSum()).isEqualTo(8);
}
@Test
public void whenAveraging_shouldAverage() throws Exception {
final Double result = givenList.stream().collect(averagingDouble(String::length));
assertThat(result).isEqualTo(2);
}
@Test
public void whenSumming_shouldSum() throws Exception {
final Double result = givenList.stream().filter(i -> true).collect(summingDouble(String::length));
assertThat(result).isEqualTo(8);
}
@Test
public void whenMaxingBy_shouldMaxBy() throws Exception {
final Optional<String> result = givenList.stream().collect(maxBy(Comparator.naturalOrder()));
assertThat(result).isPresent().hasValue("dd");
}
@Test
public void whenGroupingBy_shouldGroupBy() throws Exception {
final Map<Integer, Set<String>> result = givenList.stream().collect(groupingBy(String::length, toSet()));
assertThat(result).containsEntry(1, newHashSet("a")).containsEntry(2, newHashSet("bb", "dd")).containsEntry(3, newHashSet("ccc"));
}
@Test
public void whenCreatingCustomCollector_shouldCollect() throws Exception {
final ImmutableSet<String> result = givenList.stream().collect(toImmutableSet());
assertThat(result).isInstanceOf(ImmutableSet.class).contains("a", "bb", "ccc", "dd");
}
private static <T> ImmutableSetCollector<T> toImmutableSet() {
return new ImmutableSetCollector<>();
}
private static class ImmutableSetCollector<T> implements Collector<T, ImmutableSet.Builder<T>, ImmutableSet<T>> {
@Override
public Supplier<ImmutableSet.Builder<T>> supplier() {
return ImmutableSet::builder;
}
@Override
public BiConsumer<ImmutableSet.Builder<T>, T> accumulator() {
return ImmutableSet.Builder::add;
}
@Override
public BinaryOperator<ImmutableSet.Builder<T>> combiner() {
return (left, right) -> left.addAll(right.build());
}
@Override
public Function<ImmutableSet.Builder<T>, ImmutableSet<T>> finisher() {
return ImmutableSet.Builder::build;
}
@Override
public Set<Characteristics> characteristics() {
return Sets.immutableEnumSet(Characteristics.UNORDERED);
}
}
}

View File

@@ -1,61 +0,0 @@
package com.baeldung.counter;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
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 com.baeldung.counter.CounterUtil.MutableInteger;
@Fork(value = 1, warmups = 3)
@BenchmarkMode(Mode.All)
public class CounterStatistics {
private static final Map<String, Integer> counterMap = new HashMap<>();
private static final Map<String, MutableInteger> counterWithMutableIntMap = new HashMap<>();
private static final Map<String, int[]> counterWithIntArrayMap = new HashMap<>();
private static final Map<String, Long> counterWithLongWrapperMap = new HashMap<>();
private static final Map<String, Long> counterWithLongWrapperStreamMap = new HashMap<>();
static {
CounterUtil.COUNTRY_NAMES = new String[10000];
final String prefix = "NewString";
Random random = new Random();
for (int i=0; i<10000; i++) {
CounterUtil.COUNTRY_NAMES[i] = new String(prefix + random.nextInt(1000));
}
}
@Benchmark
public void wrapperAsCounter() {
CounterUtil.counterWithWrapperObject(counterMap);
}
@Benchmark
public void lambdaExpressionWithWrapper() {
CounterUtil.counterWithLambdaAndWrapper(counterWithLongWrapperMap);
}
@Benchmark
public void parallelStreamWithWrapper() {
CounterUtil.counterWithParallelStreamAndWrapper(counterWithLongWrapperStreamMap);
}
@Benchmark
public void mutableIntegerAsCounter() {
CounterUtil.counterWithMutableInteger(counterWithMutableIntMap);
}
@Benchmark
public void primitiveArrayAsCounter() {
CounterUtil.counterWithPrimitiveArray(counterWithIntArrayMap);
}
public static void main(String[] args) throws Exception {
org.openjdk.jmh.Main.main(args);
}
}

View File

@@ -1,53 +0,0 @@
package com.baeldung.counter;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.*;
import org.junit.Test;
import com.baeldung.counter.CounterUtil.MutableInteger;
public class CounterUnitTest {
@Test
public void whenMapWithWrapperAsCounter_runsSuccessfully() {
Map<String, Integer> counterMap = new HashMap<>();
CounterUtil.counterWithWrapperObject(counterMap);
assertEquals(3, counterMap.get("China")
.intValue());
assertEquals(2, counterMap.get("India")
.intValue());
}
@Test
public void whenMapWithLambdaAndWrapperCounter_runsSuccessfully() {
Map<String, Long> counterMap = new HashMap<>();
CounterUtil.counterWithLambdaAndWrapper(counterMap);
assertEquals(3l, counterMap.get("China")
.longValue());
assertEquals(2l, counterMap.get("India")
.longValue());
}
@Test
public void whenMapWithMutableIntegerCounter_runsSuccessfully() {
Map<String, MutableInteger> counterMap = new HashMap<>();
CounterUtil.counterWithMutableInteger(counterMap);
assertEquals(3, counterMap.get("China")
.getCount());
assertEquals(2, counterMap.get("India")
.getCount());
}
@Test
public void whenMapWithPrimitiveArray_runsSuccessfully() {
Map<String, int[]> counterMap = new HashMap<>();
CounterUtil.counterWithPrimitiveArray(counterMap);
assertEquals(3, counterMap.get("China")[0]);
assertEquals(2, counterMap.get("India")[0]);
}
}

View File

@@ -1,57 +0,0 @@
package com.baeldung.counter;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CounterUtil {
public static String[] COUNTRY_NAMES = { "China", "Australia", "India", "USA", "USSR", "UK", "China", "France", "Poland", "Austria", "India", "USA", "Egypt", "China" };
public static void counterWithWrapperObject(Map<String, Integer> counterMap) {
for (String country : COUNTRY_NAMES) {
counterMap.compute(country, (k, v) -> v == null ? 1 : v + 1);
}
}
public static void counterWithLambdaAndWrapper(Map<String, Long> counterMap) {
Stream.of(COUNTRY_NAMES)
.collect(Collectors.groupingBy(k -> k, () -> counterMap, Collectors.counting()));
}
public static void counterWithParallelStreamAndWrapper(Map<String, Long> counterMap) {
Stream.of(COUNTRY_NAMES)
.parallel()
.collect(Collectors.groupingBy(k -> k, () -> counterMap, Collectors.counting()));
}
public static class MutableInteger {
int count;
public MutableInteger(int count) {
this.count = count;
}
public void increment() {
this.count++;
}
public int getCount() {
return this.count;
}
}
public static void counterWithMutableInteger(Map<String, MutableInteger> counterMap) {
for (String country : COUNTRY_NAMES) {
counterMap.compute(country, (k, v) -> v == null ? new MutableInteger(0) : v)
.increment();
}
}
public static void counterWithPrimitiveArray(Map<String, int[]> counterMap) {
for (String country : COUNTRY_NAMES) {
counterMap.compute(country, (k, v) -> v == null ? new int[] { 0 } : v)[0]++;
}
}
}

View File

@@ -1,26 +0,0 @@
package com.baeldung.customannotations;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
public class JsonSerializerUnitTest {
@Test
public void givenObjectNotSerializedThenExceptionThrown() throws JsonSerializationException {
Object object = new Object();
ObjectToJsonConverter serializer = new ObjectToJsonConverter();
assertThrows(JsonSerializationException.class, () -> {
serializer.convertToJson(object);
});
}
@Test
public void givenObjectSerializedThenTrueReturned() throws JsonSerializationException {
Person person = new Person("soufiane", "cheouati", "34");
ObjectToJsonConverter serializer = new ObjectToJsonConverter();
String jsonString = serializer.convertToJson(person);
assertEquals("{\"personAge\":\"34\",\"firstName\":\"Soufiane\",\"lastName\":\"Cheouati\"}", jsonString);
}
}

View File

@@ -1,79 +0,0 @@
package com.baeldung.defaultistaticinterfacemethods.test;
import com.baeldung.defaultstaticinterfacemethods.model.Car;
import com.baeldung.defaultstaticinterfacemethods.model.Motorbike;
import com.baeldung.defaultstaticinterfacemethods.model.Vehicle;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
public class StaticDefaulInterfaceMethodUnitTest {
private static Car car;
private static Motorbike motorbike;
@BeforeClass
public static void setUpCarInstance() {
car = new Car("BMW");
}
@BeforeClass
public static void setUpMotorbikeInstance() {
motorbike = new Motorbike("Yamaha");
}
@Test
public void givenCarInstace_whenBrandisBMW_thenOneAssertion() {
assertThat(car.getBrand()).isEqualTo("BMW");
}
@Test
public void givenCarInstance_whenCallingSpeedUp_thenOneAssertion() {
assertThat(car.speedUp()).isEqualTo("The car is speeding up.");
}
@Test
public void givenCarInstance_whenCallingSlowDown_thenOneAssertion() {
assertThat(car.slowDown()).isEqualTo("The car is slowing down.");
}
@Test
public void givenCarInstance_whenCallingTurnAlarmOn_thenOneAssertion() {
assertThat(car.turnAlarmOn()).isEqualTo("Turning the vehice alarm on.");
}
@Test
public void givenCarInstance_whenCallingTurnAlarmOff_thenOneAssertion() {
assertThat(car.turnAlarmOff()).isEqualTo("Turning the vehicle alarm off.");
}
@Test
public void givenVehicleInterface_whenCallinggetHorsePower_thenOneAssertion() {
assertThat(Vehicle.getHorsePower(2500, 480)).isEqualTo(228);
}
@Test
public void givenMooorbikeInstace_whenBrandisYamaha_thenOneAssertion() {
assertThat(motorbike.getBrand()).isEqualTo("Yamaha");
}
@Test
public void givenMotorbikeInstance_whenCallingSpeedUp_thenOneAssertion() {
assertThat(motorbike.speedUp()).isEqualTo("The motorbike is speeding up.");
}
@Test
public void givenMotorbikeInstance_whenCallingSlowDown_thenOneAssertion() {
assertThat(motorbike.slowDown()).isEqualTo("The motorbike is slowing down.");
}
@Test
public void givenMotorbikeInstance_whenCallingTurnAlarmOn_thenOneAssertion() {
assertThat(motorbike.turnAlarmOn()).isEqualTo("Turning the vehice alarm on.");
}
@Test
public void givenMotorbikeInstance_whenCallingTurnAlarmOff_thenOneAssertion() {
assertThat(motorbike.turnAlarmOff()).isEqualTo("Turning the vehicle alarm off.");
}
}

View File

@@ -1,91 +0,0 @@
package com.baeldung.doublecolon;
import com.baeldung.doublecolon.function.TriFunction;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.function.BiFunction;
import static com.baeldung.doublecolon.ComputerUtils.*;
public class ComputerUtilsUnitTest {
@Before
public void setup() {
}
@After
public void tearDown() {
}
@Test
public void testConstructorReference() {
Computer c1 = new Computer(2015, "white");
Computer c2 = new Computer(2009, "black");
Computer c3 = new Computer(2014, "black");
BiFunction<Integer, String, Computer> c4Function = Computer::new;
Computer c4 = c4Function.apply(2013, "white");
BiFunction<Integer, String, Computer> c5Function = Computer::new;
Computer c5 = c5Function.apply(2010, "black");
BiFunction<Integer, String, Computer> c6Function = Computer::new;
Computer c6 = c6Function.apply(2008, "black");
List<Computer> inventory = Arrays.asList(c1, c2, c3, c4, c5, c6);
List<Computer> blackComputer = filter(inventory, blackPredicate);
Assert.assertEquals("The black Computers are: ", blackComputer.size(), 4);
List<Computer> after2010Computer = filter(inventory, after2010Predicate);
Assert.assertEquals("The Computer bought after 2010 are: ", after2010Computer.size(), 3);
List<Computer> before2011Computer = filter(inventory, c -> c.getAge() < 2011);
Assert.assertEquals("The Computer bought before 2011 are: ", before2011Computer.size(), 3);
inventory.sort(Comparator.comparing(Computer::getAge));
Assert.assertEquals("Oldest Computer in inventory", c6, inventory.get(0));
}
@Test
public void testStaticMethodReference() {
Computer c1 = new Computer(2015, "white", 35);
Computer c2 = new Computer(2009, "black", 65);
TriFunction<Integer, String, Integer, Computer> c6Function = Computer::new;
Computer c3 = c6Function.apply(2008, "black", 90);
List<Computer> inventory = Arrays.asList(c1, c2, c3);
inventory.forEach(ComputerUtils::repair);
Assert.assertEquals("Computer repaired", new Integer(100), c1.getHealty());
}
@Test
public void testInstanceMethodArbitraryObjectParticularType() {
Computer c1 = new Computer(2015, "white", 35);
Computer c2 = new MacbookPro(2009, "black", 65);
List<Computer> inventory = Arrays.asList(c1, c2);
inventory.forEach(Computer::turnOnPc);
}
@Test
public void testSuperMethodReference() {
final TriFunction<Integer, String, Integer, MacbookPro> integerStringIntegerObjectTriFunction = MacbookPro::new;
final MacbookPro macbookPro = integerStringIntegerObjectTriFunction.apply(2010, "black", 100);
Double initialValue = 999.99;
final Double actualValue = macbookPro.calculateValue(initialValue);
Assert.assertEquals(766.659, actualValue, 0.0);
}
}

View File

@@ -1,131 +0,0 @@
package com.baeldung.java8;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.junit.Test;
public class Java8PredicateChainUnitTest {
private List<String> names = Arrays.asList("Adam", "Alexander", "John", "Tom");
@Test
public void whenFilterList_thenSuccess() {
List<String> result = names.stream()
.filter(name -> name.startsWith("A"))
.collect(Collectors.toList());
assertEquals(2, result.size());
assertThat(result, contains("Adam", "Alexander"));
}
@Test
public void whenFilterListWithMultipleFilters_thenSuccess() {
List<String> result = names.stream()
.filter(name -> name.startsWith("A"))
.filter(name -> name.length() < 5)
.collect(Collectors.toList());
assertEquals(1, result.size());
assertThat(result, contains("Adam"));
}
@Test
public void whenFilterListWithComplexPredicate_thenSuccess() {
List<String> result = names.stream()
.filter(name -> name.startsWith("A") && name.length() < 5)
.collect(Collectors.toList());
assertEquals(1, result.size());
assertThat(result, contains("Adam"));
}
@Test
public void whenFilterListWithCombinedPredicatesInline_thenSuccess() {
List<String> result = names.stream()
.filter(((Predicate<String>) name -> name.startsWith("A")).and(name -> name.length() < 5))
.collect(Collectors.toList());
assertEquals(1, result.size());
assertThat(result, contains("Adam"));
}
@Test
public void whenFilterListWithCombinedPredicatesUsingAnd_thenSuccess() {
Predicate<String> predicate1 = str -> str.startsWith("A");
Predicate<String> predicate2 = str -> str.length() < 5;
List<String> result = names.stream()
.filter(predicate1.and(predicate2))
.collect(Collectors.toList());
assertEquals(1, result.size());
assertThat(result, contains("Adam"));
}
@Test
public void whenFilterListWithCombinedPredicatesUsingOr_thenSuccess() {
Predicate<String> predicate1 = str -> str.startsWith("J");
Predicate<String> predicate2 = str -> str.length() < 4;
List<String> result = names.stream()
.filter(predicate1.or(predicate2))
.collect(Collectors.toList());
assertEquals(2, result.size());
assertThat(result, contains("John", "Tom"));
}
@Test
public void whenFilterListWithCombinedPredicatesUsingOrAndNegate_thenSuccess() {
Predicate<String> predicate1 = str -> str.startsWith("J");
Predicate<String> predicate2 = str -> str.length() < 4;
List<String> result = names.stream()
.filter(predicate1.or(predicate2.negate()))
.collect(Collectors.toList());
assertEquals(3, result.size());
assertThat(result, contains("Adam", "Alexander", "John"));
}
@Test
public void whenFilterListWithCollectionOfPredicatesUsingAnd_thenSuccess() {
List<Predicate<String>> allPredicates = new ArrayList<Predicate<String>>();
allPredicates.add(str -> str.startsWith("A"));
allPredicates.add(str -> str.contains("d"));
allPredicates.add(str -> str.length() > 4);
List<String> result = names.stream()
.filter(allPredicates.stream()
.reduce(x -> true, Predicate::and))
.collect(Collectors.toList());
assertEquals(1, result.size());
assertThat(result, contains("Alexander"));
}
@Test
public void whenFilterListWithCollectionOfPredicatesUsingOr_thenSuccess() {
List<Predicate<String>> allPredicates = new ArrayList<Predicate<String>>();
allPredicates.add(str -> str.startsWith("A"));
allPredicates.add(str -> str.contains("d"));
allPredicates.add(str -> str.length() > 4);
List<String> result = names.stream()
.filter(allPredicates.stream()
.reduce(x -> false, Predicate::or))
.collect(Collectors.toList());
assertEquals(2, result.size());
assertThat(result, contains("Adam", "Alexander"));
}
}

View File

@@ -1,60 +0,0 @@
package com.baeldung.java8;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.junit.Assert.assertEquals;
public class UnsignedArithmeticUnitTest {
@Test
public void whenDoublingALargeByteNumber_thenOverflow() {
byte b1 = 100;
byte b2 = (byte) (b1 << 1);
assertEquals(-56, b2);
}
@Test
public void whenComparingNumbers_thenNegativeIsInterpretedAsUnsigned() {
int positive = Integer.MAX_VALUE;
int negative = Integer.MIN_VALUE;
int signedComparison = Integer.compare(positive, negative);
assertEquals(1, signedComparison);
int unsignedComparison = Integer.compareUnsigned(positive, negative);
assertEquals(-1, unsignedComparison);
assertEquals(negative, positive + 1);
}
@Test
public void whenDividingNumbers_thenNegativeIsInterpretedAsUnsigned() {
int positive = Integer.MAX_VALUE;
int negative = Integer.MIN_VALUE;
assertEquals(-1, negative / positive);
assertEquals(1, Integer.divideUnsigned(negative, positive));
assertEquals(-1, negative % positive);
assertEquals(1, Integer.remainderUnsigned(negative, positive));
}
@Test
public void whenParsingNumbers_thenNegativeIsInterpretedAsUnsigned() {
Throwable thrown = catchThrowable(() -> Integer.parseInt("2147483648"));
assertThat(thrown).isInstanceOf(NumberFormatException.class);
assertEquals(Integer.MAX_VALUE + 1, Integer.parseUnsignedInt("2147483648"));
}
@Test
public void whenFormattingNumbers_thenNegativeIsInterpretedAsUnsigned() {
String signedString = Integer.toString(Integer.MIN_VALUE);
assertEquals("-2147483648", signedString);
String unsignedString = Integer.toUnsignedString(Integer.MIN_VALUE);
assertEquals("2147483648", unsignedString);
}
}

View File

@@ -1,110 +0,0 @@
package com.baeldung.java8.optional;
import org.junit.Before;
import org.junit.Test;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.stream.Stream;
import static org.junit.Assert.*;
public class OptionalChainingUnitTest {
private boolean getEmptyEvaluated;
private boolean getHelloEvaluated;
private boolean getByeEvaluated;
@Before
public void setUp() {
getEmptyEvaluated = false;
getHelloEvaluated = false;
getByeEvaluated = false;
}
@Test
public void givenThreeOptionals_whenChaining_thenFirstNonEmptyIsReturned() {
Optional<String> found = Stream.of(getEmpty(), getHello(), getBye())
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst();
assertEquals(getHello(), found);
}
@Test
public void givenTwoEmptyOptionals_whenChaining_thenEmptyOptionalIsReturned() {
Optional<String> found = Stream.of(getEmpty(), getEmpty())
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst();
assertFalse(found.isPresent());
}
@Test
public void givenTwoEmptyOptionals_whenChaining_thenDefaultIsReturned() {
String found = Stream.<Supplier<Optional<String>>>of(
() -> createOptional("empty"),
() -> createOptional("empty")
)
.map(Supplier::get)
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst()
.orElseGet(() -> "default");
assertEquals("default", found);
}
@Test
public void givenThreeOptionals_whenChaining_thenFirstNonEmptyIsReturnedAndRestNotEvaluated() {
Optional<String> found = Stream.<Supplier<Optional<String>>>of(this::getEmpty, this::getHello, this::getBye)
.map(Supplier::get)
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst();
assertTrue(this.getEmptyEvaluated);
assertTrue(this.getHelloEvaluated);
assertFalse(this.getByeEvaluated);
assertEquals(getHello(), found);
}
@Test
public void givenTwoOptionalsReturnedByOneArgMethod_whenChaining_thenFirstNonEmptyIsReturned() {
Optional<String> found = Stream.<Supplier<Optional<String>>>of(
() -> createOptional("empty"),
() -> createOptional("hello")
)
.map(Supplier::get)
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst();
assertEquals(createOptional("hello"), found);
}
private Optional<String> getEmpty() {
this.getEmptyEvaluated = true;
return Optional.empty();
}
private Optional<String> getHello() {
this.getHelloEvaluated = true;
return Optional.of("hello");
}
private Optional<String> getBye() {
this.getByeEvaluated = true;
return Optional.of("bye");
}
private Optional<String> createOptional(String input) {
if (input == null || "".equals(input) || "empty".equals(input)) {
return Optional.empty();
}
return Optional.of(input);
}
}

View File

@@ -1,273 +0,0 @@
package com.baeldung.java8.optional;
import com.baeldung.optional.Modem;
import com.baeldung.optional.Person;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;
import static org.junit.Assert.*;
public class OptionalUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(OptionalUnitTest.class);
// creating Optional
@Test
public void whenCreatesEmptyOptional_thenCorrect() {
Optional<String> empty = Optional.empty();
assertFalse(empty.isPresent());
}
@Test
public void givenNonNull_whenCreatesNonNullable_thenCorrect() {
String name = "baeldung";
Optional<String> opt = Optional.of(name);
assertTrue(opt.isPresent());
}
@Test(expected = NullPointerException.class)
public void givenNull_whenThrowsErrorOnCreate_thenCorrect() {
String name = null;
Optional.of(name);
}
@Test
public void givenNonNull_whenCreatesOptional_thenCorrect() {
String name = "baeldung";
Optional<String> opt = Optional.of(name);
assertTrue(opt.isPresent());
}
@Test
public void givenNonNull_whenCreatesNullable_thenCorrect() {
String name = "baeldung";
Optional<String> opt = Optional.ofNullable(name);
assertTrue(opt.isPresent());
}
@Test
public void givenNull_whenCreatesNullable_thenCorrect() {
String name = null;
Optional<String> opt = Optional.ofNullable(name);
assertFalse(opt.isPresent());
}
// Checking Value With isPresent()
@Test
public void givenOptional_whenIsPresentWorks_thenCorrect() {
Optional<String> opt = Optional.of("Baeldung");
assertTrue(opt.isPresent());
opt = Optional.ofNullable(null);
assertFalse(opt.isPresent());
}
// Condition Action With ifPresent()
@Test
public void givenOptional_whenIfPresentWorks_thenCorrect() {
Optional<String> opt = Optional.of("baeldung");
opt.ifPresent(name -> LOG.debug("{}", name.length()));
}
// returning Value With get()
@Test
public void givenOptional_whenGetsValue_thenCorrect() {
Optional<String> opt = Optional.of("baeldung");
String name = opt.get();
assertEquals("baeldung", name);
}
@Test(expected = NoSuchElementException.class)
public void givenOptionalWithNull_whenGetThrowsException_thenCorrect() {
Optional<String> opt = Optional.ofNullable(null);
String name = opt.get();
}
// Conditional Return With filter()
@Test
public void whenOptionalFilterWorks_thenCorrect() {
Integer year = 2016;
Optional<Integer> yearOptional = Optional.of(year);
boolean is2016 = yearOptional.filter(y -> y == 2016)
.isPresent();
assertTrue(is2016);
boolean is2017 = yearOptional.filter(y -> y == 2017)
.isPresent();
assertFalse(is2017);
}
@Test
public void whenFiltersWithoutOptional_thenCorrect() {
assertTrue(priceIsInRange1(new Modem(10.0)));
assertFalse(priceIsInRange1(new Modem(9.9)));
assertFalse(priceIsInRange1(new Modem(null)));
assertFalse(priceIsInRange1(new Modem(15.5)));
assertFalse(priceIsInRange1(null));
}
@Test
public void whenFiltersWithOptional_thenCorrect() {
assertTrue(priceIsInRange2(new Modem(10.0)));
assertFalse(priceIsInRange2(new Modem(9.9)));
assertFalse(priceIsInRange2(new Modem(null)));
assertFalse(priceIsInRange2(new Modem(15.5)));
assertFalse(priceIsInRange1(null));
}
public boolean priceIsInRange1(Modem modem) {
boolean isInRange = false;
if (modem != null && modem.getPrice() != null && (modem.getPrice() >= 10 && modem.getPrice() <= 15)) {
isInRange = true;
}
return isInRange;
}
public boolean priceIsInRange2(Modem modem2) {
return Optional.ofNullable(modem2)
.map(Modem::getPrice)
.filter(p -> p >= 10)
.filter(p -> p <= 15)
.isPresent();
}
// Transforming Value With map()
@Test
public void givenOptional_whenMapWorks_thenCorrect() {
List<String> companyNames = Arrays.asList("paypal", "oracle", "", "microsoft", "", "apple");
Optional<List<String>> listOptional = Optional.of(companyNames);
int size = listOptional.map(List::size)
.orElse(0);
assertEquals(6, size);
}
@Test
public void givenOptional_whenMapWorks_thenCorrect2() {
String name = "baeldung";
Optional<String> nameOptional = Optional.of(name);
int len = nameOptional.map(String::length)
.orElse(0);
assertEquals(8, len);
}
@Test
public void givenOptional_whenMapWorksWithFilter_thenCorrect() {
String password = " password ";
Optional<String> passOpt = Optional.of(password);
boolean correctPassword = passOpt.filter(pass -> pass.equals("password"))
.isPresent();
assertFalse(correctPassword);
correctPassword = passOpt.map(String::trim)
.filter(pass -> pass.equals("password"))
.isPresent();
assertTrue(correctPassword);
}
// Transforming Value With flatMap()
@Test
public void givenOptional_whenFlatMapWorks_thenCorrect2() {
Person person = new Person("john", 26);
Optional<Person> personOptional = Optional.of(person);
Optional<Optional<String>> nameOptionalWrapper = personOptional.map(Person::getName);
Optional<String> nameOptional = nameOptionalWrapper.orElseThrow(IllegalArgumentException::new);
String name1 = nameOptional.orElseThrow(IllegalArgumentException::new);
assertEquals("john", name1);
String name = personOptional.flatMap(Person::getName)
.orElseThrow(IllegalArgumentException::new);
assertEquals("john", name);
}
@Test
public void givenOptional_whenFlatMapWorksWithFilter_thenCorrect() {
Person person = new Person("john", 26);
person.setPassword("password");
Optional<Person> personOptional = Optional.of(person);
String password = personOptional.flatMap(Person::getPassword)
.filter(cleanPass -> cleanPass.equals("password"))
.orElseThrow(IllegalArgumentException::new);
assertEquals("password", password);
}
// Default Value With orElse
@Test
public void whenOrElseWorks_thenCorrect() {
String nullName = null;
String name = Optional.ofNullable(nullName)
.orElse("john");
assertEquals("john", name);
}
// Default Value With orElseGet
@Test
public void whenOrElseGetWorks_thenCorrect() {
String nullName = null;
String name = Optional.ofNullable(nullName)
.orElseGet(() -> "john");
assertEquals("john", name);
}
@Test
public void whenOrElseGetAndOrElseOverlap_thenCorrect() {
String text = null;
LOG.debug("Using orElseGet:");
String defaultText = Optional.ofNullable(text)
.orElseGet(this::getMyDefault);
assertEquals("Default Value", defaultText);
LOG.debug("Using orElse:");
defaultText = Optional.ofNullable(text)
.orElse(getMyDefault());
assertEquals("Default Value", defaultText);
}
@Test
public void whenOrElseGetAndOrElseDiffer_thenCorrect() {
String text = "Text present";
LOG.debug("Using orElseGet:");
String defaultText = Optional.ofNullable(text)
.orElseGet(this::getMyDefault);
assertEquals("Text present", defaultText);
LOG.debug("Using orElse:");
defaultText = Optional.ofNullable(text)
.orElse(getMyDefault());
assertEquals("Text present", defaultText);
}
// Exceptions With orElseThrow
@Test(expected = IllegalArgumentException.class)
public void whenOrElseThrowWorks_thenCorrect() {
String nullName = null;
String name = Optional.ofNullable(nullName)
.orElseThrow(IllegalArgumentException::new);
}
public String getMyDefault() {
LOG.debug("Getting default value...");
return "Default Value";
}
// Uncomment code when code base is compatiable with Java 11
// @Test
// public void givenAnEmptyOptional_thenIsEmptyBehavesAsExpected() {
// Optional<String> opt = Optional.of("Baeldung");
// assertFalse(opt.isEmpty());
//
// opt = Optional.ofNullable(null);
// assertTrue(opt.isEmpty());
// }
}

View File

@@ -1,44 +0,0 @@
package com.baeldung.java8.optional;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.junit.Assert.*;
import com.baeldung.optional.OrElseAndOrElseGet;
public class OrElseAndOrElseGetUnitTest {
private OrElseAndOrElseGet orElsevsOrElseGet = new OrElseAndOrElseGet();
private static final Logger LOG = LoggerFactory.getLogger(OrElseAndOrElseGetUnitTest.class);
@Test
public void givenNonEmptyOptional_whenOrElseUsed_thenGivenStringReturned() {
LOG.info("In givenNonEmptyOptional_whenOrElseUsed_thenGivenStringReturned()");
String name = orElsevsOrElseGet.getNameUsingOrElse("baeldung");
assertEquals(name, "baeldung");
}
@Test
public void givenEmptyOptional_whenOrElseUsed_thenRandomStringReturned() {
LOG.info("In givenEmptyOptional_whenOrElseUsed_thenRandomStringReturned()");
String name = orElsevsOrElseGet.getNameUsingOrElse(null);
assertTrue(orElsevsOrElseGet.names.contains(name));
}
@Test
public void givenNonEmptyOptional_whenOrElseGetUsed_thenGivenStringReturned() {
LOG.info("In givenNonEmptyOptional_whenOrElseGetUsed_thenGivenStringReturned()");
String name = orElsevsOrElseGet.getNameUsingOrElseGet("baeldung");
assertEquals(name, "baeldung");
}
@Test
public void givenEmptyOptional_whenOrElseGetUsed_thenRandomStringReturned() {
LOG.info("In givenEmptyOptional_whenOrElseGetUsed_thenRandomStringReturned()");
String name = orElsevsOrElseGet.getNameUsingOrElseGet(null);
assertTrue(orElsevsOrElseGet.names.contains(name));
}
}

View File

@@ -1,89 +0,0 @@
package com.baeldung.math;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class MathNewMethodsUnitTest {
@Test
public void whenAddExactToInteger_thenExpectCorrectArithmeticResult() {
assertEquals(150, Math.addExact(100, 50)); // Returns 150
}
@Test
public void whenSubstractExactFromInteger_thenExpectCorrectArithmeticResult() {
assertEquals(50, Math.subtractExact(100, 50)); // Returns 50
}
@Test
public void whenDecrementExactInteger_thenExpectCorrectArithmeticResult() {
assertEquals(99, Math.decrementExact(100)); // Returns 99
}
@Test
public void whenIncrementExactToInteger_thenExpectCorrectArithmeticResult() {
assertEquals(101, Math.incrementExact(100)); // Returns 101
}
@Test
public void whenMultiplyExactTwoIntegers_thenExpectCorrectArithmeticResult() {
assertEquals(500, Math.multiplyExact(100, 5)); // Returns 500
}
@Test
public void whenNegateExactInteger_thenExpectCorrectArithmeticResult() {
assertEquals(-100, Math.negateExact(100)); // Returns -100
}
@Test(expected = ArithmeticException.class)
public void whenAddToMaxInteger_thenThrowsArithmeticException() {
Math.addExact(Integer.MAX_VALUE, 1); // Throws ArithmeticException
}
@Test(expected = ArithmeticException.class)
public void whenDecrementMinInteger_thenThrowsArithmeticException() {
Math.decrementExact(Integer.MIN_VALUE); // Throws ArithmeticException
}
@Test(expected = ArithmeticException.class)
public void whenIncrementMaxLong_thenThrowsArithmeticException() {
Math.incrementExact(Long.MAX_VALUE); // Throws ArithmeticException
}
@Test(expected = ArithmeticException.class)
public void whenMultiplyMaxLong_thenThrowsArithmeticException() {
Math.multiplyExact(Long.MAX_VALUE, 2); // Throws ArithmeticException
}
@Test(expected = ArithmeticException.class)
public void whenNegateMinInteger_thenThrowsArithmeticException() {
Math.negateExact(Integer.MIN_VALUE); // MinInt value: 2.147.483.648, but MaxInt Value: 2.147.483.647 => Throws ArithmeticException
}
@Test(expected = ArithmeticException.class)
public void whenSubstractFromMinInteger_thenThrowsArithmeticException() {
Math.subtractExact(Integer.MIN_VALUE, 1);
}
@Test
public void whenFloorDivTwoIntegers_thenExpectCorrectArithmeticResult() {
assertEquals(3, Math.floorDiv(7, 2)); // Exact quotient is 3.5 so floor(3.5) == 3
assertEquals(-4, Math.floorDiv(-7, 2)); // Exact quotient is -3.5 so floor(-3.5) == -4
}
@Test
public void whenModDivTwoIntegers_thenExpectCorrectArithmeticResult() {
assertEquals(2, Math.floorMod(5, 3)); // Returns 2: floorMod for positive numbers returns the same as % operator
assertEquals(1, Math.floorMod(-5, 3)); // Returns 1 and not 2 because floorDiv(-5, 3) is -2 and not -1 and (-2*3) + (1) = -5
}
@Test
public void whenNextDownOfDouble_thenExpectCorrectNumber() {
double number = 3.0;
double expected = 2.999999999999;
double delta = 0.00000001;
assertEquals(expected, Math.nextDown(number), delta); // The delta defines the accepted error range
}
}

View File

@@ -1,39 +0,0 @@
package com.baeldung.reduceIfelse;
import com.baeldung.reducingIfElse.AddCommand;
import com.baeldung.reducingIfElse.Calculator;
import com.baeldung.reducingIfElse.Operator;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class CalculatorUnitTest {
@Test
public void whenCalculateUsingStringOperator_thenReturnCorrectResult() {
Calculator calculator = new Calculator();
int result = calculator.calculate(3, 4, "add");
assertEquals(7, result);
}
@Test
public void whenCalculateUsingEnumOperator_thenReturnCorrectResult() {
Calculator calculator = new Calculator();
int result = calculator.calculate(3, 4, Operator.valueOf("ADD"));
assertEquals(7, result);
}
@Test
public void whenCalculateUsingCommand_thenReturnCorrectResult() {
Calculator calculator = new Calculator();
int result = calculator.calculate(new AddCommand(3, 7));
assertEquals(10, result);
}
@Test
public void whenCalculateUsingFactory_thenReturnCorrectResult() {
Calculator calculator = new Calculator();
int result = calculator.calculateUsingFactory(3, 4, "add");
assertEquals(7, result);
}
}

View File

@@ -1,23 +0,0 @@
package com.baeldung.reduceIfelse;
import com.baeldung.reducingIfElse.Expression;
import com.baeldung.reducingIfElse.Operator;
import com.baeldung.reducingIfElse.Result;
import com.baeldung.reducingIfElse.RuleEngine;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class RuleEngineUnitTest {
@Test
public void whenNumbersGivenToRuleEngine_thenReturnCorrectResult() {
Expression expression = new Expression(5, 5, Operator.ADD);
RuleEngine engine = new RuleEngine();
Result result = engine.process(expression);
assertNotNull(result);
assertEquals(10, result.getValue());
}
}

View File

@@ -1,41 +0,0 @@
package com.baeldung.stream.conditional;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import org.junit.Assert;
import org.junit.Test;
public class StreamForEachIfElseUnitTest {
@Test
public final void givenIntegerStream_whenCheckingIntegerParityWithIfElse_thenEnsureCorrectParity() {
List<Integer> ints = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
ints.stream()
.forEach(i -> {
if (i.intValue() % 2 == 0) {
Assert.assertTrue(i.intValue() + " is not even", i.intValue() % 2 == 0);
} else {
Assert.assertTrue(i.intValue() + " is not odd", i.intValue() % 2 != 0);
}
});
}
@Test
public final void givenIntegerStream_whenCheckingIntegerParityWithStreamFilter_thenEnsureCorrectParity() {
List<Integer> ints = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Stream<Integer> evenIntegers = ints.stream()
.filter(i -> i.intValue() % 2 == 0);
Stream<Integer> oddIntegers = ints.stream()
.filter(i -> i.intValue() % 2 != 0);
evenIntegers.forEach(i -> Assert.assertTrue(i.intValue() + " is not even", i.intValue() % 2 == 0));
oddIntegers.forEach(i -> Assert.assertTrue(i.intValue() + " is not odd", i.intValue() % 2 != 0));
}
}

View File

@@ -1,42 +0,0 @@
package com.baeldung.time;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ Instant.class })
public class InstantUnitTest {
@Test
public void givenInstantMock_whenNow_thenGetFixedInstant() {
String instantExpected = "2014-12-22T10:15:30Z";
Clock clock = Clock.fixed(Instant.parse(instantExpected), ZoneId.of("UTC"));
Instant instant = Instant.now(clock);
mockStatic(Instant.class);
when(Instant.now()).thenReturn(instant);
Instant now = Instant.now();
assertThat(now.toString()).isEqualTo(instantExpected);
}
@Test
public void givenFixedClock_whenNow_thenGetFixedInstant() {
String instantExpected = "2014-12-22T10:15:30Z";
Clock clock = Clock.fixed(Instant.parse(instantExpected), ZoneId.of("UTC"));
Instant instant = Instant.now(clock);
assertThat(instant.toString()).isEqualTo(instantExpected);
}
}

View File

@@ -1,47 +0,0 @@
package com.baeldung.time;
import mockit.Expectations;
import mockit.Mock;
import mockit.MockUp;
import org.junit.jupiter.api.Test;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
import static org.assertj.core.api.Assertions.assertThat;
public class InstantWithJMockUnitTest {
@Test
public void givenInstantWithJMock_whenNow_thenGetFixedInstant() {
String instantExpected = "2014-12-21T10:15:30Z";
Clock clock = Clock.fixed(Instant.parse(instantExpected), ZoneId.of("UTC"));
new MockUp<Instant>() {
@Mock
public Instant now() {
return Instant.now(clock);
}
};
Instant now = Instant.now();
assertThat(now.toString()).isEqualTo(instantExpected);
}
@Test
public void givenInstantWithExpectations_whenNow_thenGetFixedInstant() {
Clock clock = Clock.fixed(Instant.parse("2014-12-23T10:15:30.00Z"), ZoneId.of("UTC"));
Instant instantExpected = Instant.now(clock);
new Expectations(Instant.class) {
{
Instant.now();
result = instantExpected;
}
};
Instant now = Instant.now();
assertThat(now).isEqualTo(instantExpected);
}
}

View File

@@ -1,43 +0,0 @@
package com.baeldung.time;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.time.Clock;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ LocalDateTime.class })
public class LocalDateTimeUnitTest {
@Test
public void givenLocalDateTimeMock_whenNow_thenGetFixedLocalDateTime() {
Clock clock = Clock.fixed(Instant.parse("2014-12-22T10:15:30.00Z"), ZoneId.of("UTC"));
LocalDateTime dateTime = LocalDateTime.now(clock);
mockStatic(LocalDateTime.class);
when(LocalDateTime.now()).thenReturn(dateTime);
String dateTimeExpected = "2014-12-22T10:15:30";
LocalDateTime now = LocalDateTime.now();
assertThat(now).isEqualTo(dateTimeExpected);
}
@Test
public void givenFixedClock_whenNow_thenGetFixedLocalDateTime() {
Clock clock = Clock.fixed(Instant.parse("2014-12-22T10:15:30.00Z"), ZoneId.of("UTC"));
String dateTimeExpected = "2014-12-22T10:15:30";
LocalDateTime dateTime = LocalDateTime.now(clock);
assertThat(dateTime).isEqualTo(dateTimeExpected);
}
}

View File

@@ -1,48 +0,0 @@
package com.baeldung.time;
import mockit.Expectations;
import mockit.Mock;
import mockit.MockUp;
import org.junit.jupiter.api.Test;
import java.time.Clock;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import static org.assertj.core.api.Assertions.assertThat;
public class LocalDateTimeWithJMockUnitTest {
@Test
public void givenLocalDateTimeWithJMock_whenNow_thenGetFixedLocalDateTime() {
Clock clock = Clock.fixed(Instant.parse("2014-12-21T10:15:30.00Z"), ZoneId.of("UTC"));
new MockUp<LocalDateTime>() {
@Mock
public LocalDateTime now() {
return LocalDateTime.now(clock);
}
};
String dateTimeExpected = "2014-12-21T10:15:30";
LocalDateTime now = LocalDateTime.now();
assertThat(now).isEqualTo(dateTimeExpected);
}
@Test
public void givenLocalDateTimeWithExpectations_whenNow_thenGetFixedLocalDateTime() {
Clock clock = Clock.fixed(Instant.parse("2014-12-23T10:15:30.00Z"), ZoneId.of("UTC"));
LocalDateTime dateTimeExpected = LocalDateTime.now(clock);
new Expectations(LocalDateTime.class) {
{
LocalDateTime.now();
result = dateTimeExpected;
}
};
LocalDateTime now = LocalDateTime.now();
assertThat(now).isEqualTo(dateTimeExpected);
}
}