[BAEL-13506] - Split or move core-java-8 module (#7790)
This commit is contained in:
committed by
Josh Cummings
parent
7d65b1fb24
commit
f2cac1ab7c
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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]);
|
||||
}
|
||||
}
|
||||
@@ -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]++;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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.");
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
// }
|
||||
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user