[BAEL-9555] - Created a core-java-modules folder

This commit is contained in:
amit2103
2019-05-05 17:22:09 +05:30
parent 8b63b0d90a
commit 3bae5e5334
1480 changed files with 25600 additions and 5594 deletions

View File

@@ -0,0 +1,231 @@
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

@@ -0,0 +1,61 @@
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

@@ -0,0 +1,53 @@
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

@@ -0,0 +1,57 @@
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

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

@@ -0,0 +1,79 @@
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

@@ -0,0 +1,91 @@
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

@@ -0,0 +1,187 @@
package com.baeldung.functionalinterface;
import com.google.common.util.concurrent.Uninterruptibles;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.Assert.*;
public class FunctionalInterfaceUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(FunctionalInterfaceUnitTest.class);
@Test
public void whenPassingLambdaToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() {
Map<String, Integer> nameMap = new HashMap<>();
Integer value = nameMap.computeIfAbsent("John", String::length);
assertEquals(new Integer(4), nameMap.get("John"));
assertEquals(new Integer(4), value);
}
@Test
public void whenPassingMethodReferenceToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() {
Map<String, Integer> nameMap = new HashMap<>();
Integer value = nameMap.computeIfAbsent("John", String::length);
assertEquals(new Integer(4), nameMap.get("John"));
assertEquals(new Integer(4), value);
}
@Test
public void whenUsingCustomFunctionalInterfaceForPrimitives_thenCanUseItAsLambda() {
short[] array = { (short) 1, (short) 2, (short) 3 };
byte[] transformedArray = transformArray(array, s -> (byte) (s * 2));
byte[] expectedArray = { (byte) 2, (byte) 4, (byte) 6 };
assertArrayEquals(expectedArray, transformedArray);
}
@Test
public void whenUsingBiFunction_thenCanUseItToReplaceMapValues() {
Map<String, Integer> salaries = new HashMap<>();
salaries.put("John", 40000);
salaries.put("Freddy", 30000);
salaries.put("Samuel", 50000);
salaries.replaceAll((name, oldValue) -> name.equals("Freddy") ? oldValue : oldValue + 10000);
assertEquals(new Integer(50000), salaries.get("John"));
assertEquals(new Integer(30000), salaries.get("Freddy"));
assertEquals(new Integer(60000), salaries.get("Samuel"));
}
@Test
public void whenPassingLambdaToThreadConstructor_thenLambdaInferredToRunnable() {
Thread thread = new Thread(() -> LOG.debug("Hello From Another Thread"));
thread.start();
}
@Test
public void whenUsingSupplierToGenerateNumbers_thenCanUseItInStreamGenerate() {
int[] fibs = { 0, 1 };
Stream<Integer> fibonacci = Stream.generate(() -> {
int result = fibs[1];
int fib3 = fibs[0] + fibs[1];
fibs[0] = fibs[1];
fibs[1] = fib3;
return result;
});
List<Integer> fibonacci5 = fibonacci.limit(5)
.collect(Collectors.toList());
assertEquals(new Integer(1), fibonacci5.get(0));
assertEquals(new Integer(1), fibonacci5.get(1));
assertEquals(new Integer(2), fibonacci5.get(2));
assertEquals(new Integer(3), fibonacci5.get(3));
assertEquals(new Integer(5), fibonacci5.get(4));
}
@Test
public void whenUsingConsumerInForEach_thenConsumerExecutesForEachListElement() {
List<String> names = Arrays.asList("John", "Freddy", "Samuel");
names.forEach(name -> LOG.debug("Hello, " + name));
}
@Test
public void whenUsingBiConsumerInForEach_thenConsumerExecutesForEachMapElement() {
Map<String, Integer> ages = new HashMap<>();
ages.put("John", 25);
ages.put("Freddy", 24);
ages.put("Samuel", 30);
ages.forEach((name, age) -> LOG.debug(name + " is " + age + " years old"));
}
@Test
public void whenUsingPredicateInFilter_thenListValuesAreFilteredOut() {
List<String> names = Arrays.asList("Angela", "Aaron", "Bob", "Claire", "David");
List<String> namesWithA = names.stream()
.filter(name -> name.startsWith("A"))
.collect(Collectors.toList());
assertEquals(2, namesWithA.size());
assertTrue(namesWithA.contains("Angela"));
assertTrue(namesWithA.contains("Aaron"));
}
@Test
public void whenUsingUnaryOperatorWithReplaceAll_thenAllValuesInTheListAreReplaced() {
List<String> names = Arrays.asList("bob", "josh", "megan");
names.replaceAll(String::toUpperCase);
assertEquals("BOB", names.get(0));
assertEquals("JOSH", names.get(1));
assertEquals("MEGAN", names.get(2));
}
@Test
public void whenUsingBinaryOperatorWithStreamReduce_thenResultIsSumOfValues() {
List<Integer> values = Arrays.asList(3, 5, 8, 9, 12);
int sum = values.stream()
.reduce(0, (i1, i2) -> i1 + i2);
assertEquals(37, sum);
}
@Test
public void whenComposingTwoFunctions_thenFunctionsExecuteSequentially() {
Function<Integer, String> intToString = Object::toString;
Function<String, String> quote = s -> "'" + s + "'";
Function<Integer, String> quoteIntToString = quote.compose(intToString);
assertEquals("'5'", quoteIntToString.apply(5));
}
@Test
public void whenUsingSupplierToGenerateValue_thenValueIsGeneratedLazily() {
Supplier<Double> lazyValue = () -> {
Uninterruptibles.sleepUninterruptibly(1000, TimeUnit.MILLISECONDS);
return 9d;
};
double valueSquared = squareLazy(lazyValue);
assertEquals(81d, valueSquared, 0);
}
//
public double squareLazy(Supplier<Double> lazyValue) {
return Math.pow(lazyValue.get(), 2);
}
public byte[] transformArray(short[] array, ShortToByteFunction function) {
byte[] transformedArray = new byte[array.length];
for (int i = 0; i < array.length; i++) {
transformedArray[i] = function.applyAsByte(array[i]);
}
return transformedArray;
}
}

View File

@@ -0,0 +1,8 @@
package com.baeldung.functionalinterface;
@FunctionalInterface
public interface ShortToByteFunction {
byte applyAsByte(short s);
}

View File

@@ -0,0 +1,110 @@
package com.baeldung.internationalization;
import org.junit.Assert;
import org.junit.Test;
import java.text.DateFormat;
import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;
public class DateFormatUnitTest {
@Test
public void givenGregorianCalendar_whenLocaleSpecificDateInstance_givenLanguageSpecificMonths() {
GregorianCalendar gregorianCalendar = new GregorianCalendar(2018, 1, 1, 10, 15, 20);
Date date = gregorianCalendar.getTime();
DateFormat itInstance = DateFormat.getDateInstance(DateFormat.FULL, Locale.ITALY);
DateFormat usInstance = DateFormat.getDateInstance(DateFormat.FULL, Locale.US);
Assert.assertEquals("giovedì 1 febbraio 2018", itInstance.format(date));
Assert.assertEquals("Thursday, February 1, 2018", usInstance.format(date));
}
@Test
public void givenGregorianCalendar_whenDateInstanceWithDifferentFormats_givenSpecificDateFormatting() {
GregorianCalendar gregorianCalendar = new GregorianCalendar(2018, 1, 1, 10, 15, 20);
Date date = gregorianCalendar.getTime();
DateFormat fullInstance = DateFormat.getDateInstance(DateFormat.FULL, Locale.ITALY);
DateFormat mediumInstance = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.ITALY);
Assert.assertEquals("giovedì 1 febbraio 2018", fullInstance.format(date));
Assert.assertEquals("1-feb-2018", mediumInstance.format(date));
}
@Test
public void givenGregorianCalendar_whenTimeInstanceWithDifferentFormats_givenSpecificTimeFormatting() {
GregorianCalendar gregorianCalendar = new GregorianCalendar(2018, 1, 1, 10, 15, 20);
gregorianCalendar.setTimeZone(TimeZone.getTimeZone("CET"));
TimeZone.setDefault(TimeZone.getTimeZone("CET"));
Date date = gregorianCalendar.getTime();
DateFormat fullInstance = DateFormat.getTimeInstance(DateFormat.FULL, Locale.ITALY);
DateFormat mediumInstance = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.ITALY);
Assert.assertEquals("10.15.20 CET", fullInstance.format(date));
Assert.assertEquals("10.15.20" , mediumInstance.format(date));
}
@Test
public void givenGregorianCalendar_whenDateTimeInstanceWithDifferentFormats_givenSpecificDateTimeFormatting() {
GregorianCalendar gregorianCalendar = new GregorianCalendar(2018, 1, 1, 10, 15, 20);
gregorianCalendar.setTimeZone(TimeZone.getTimeZone("CET"));
TimeZone.setDefault(TimeZone.getTimeZone("CET"));
Date date = gregorianCalendar.getTime();
DateFormat ffInstance = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, Locale.ITALY);
DateFormat smInstance = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, Locale.ITALY);
Assert.assertEquals("giovedì 1 febbraio 2018 10.15.20 CET", ffInstance.format(date));
Assert.assertEquals("01/02/18 10.15.20", smInstance.format(date));
}
@Test
public void givenGregorianCalendar_whenLocaleSpecificDateTimeInstance_givenLocaleSpecificFormatting() {
GregorianCalendar gregorianCalendar = new GregorianCalendar(2018, 1, 1, 10, 15, 20);
gregorianCalendar.setTimeZone(TimeZone.getTimeZone("CET"));
TimeZone.setDefault(TimeZone.getTimeZone("CET"));
Date date = gregorianCalendar.getTime();
DateFormat itInstance = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, Locale.ITALY);
DateFormat jpInstance = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, Locale.JAPAN);
Assert.assertEquals("giovedì 1 febbraio 2018 10.15.20 CET", itInstance.format(date));
Assert.assertEquals("2018年2月1日 10時15分20秒 CET", jpInstance.format(date));
}
@Test
public void givenGregorianCalendar_whenCustomizedSimpleDateFormat_thenSpecificMonthRepresentations() {
GregorianCalendar gregorianCalendar = new GregorianCalendar(2018, 1, 1, 10, 15, 20);
Date date = gregorianCalendar.getTime();
Locale.setDefault(new Locale("pl", "PL"));
SimpleDateFormat fullMonthDateFormat = new SimpleDateFormat("dd-MMMM-yyyy HH:mm:ss:SSS");
SimpleDateFormat shortMonthsimpleDateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss:SSS");
Assert.assertEquals("01-lutego-2018 10:15:20:000", fullMonthDateFormat.format(date));
Assert.assertEquals("01-02-2018 10:15:20:000" , shortMonthsimpleDateFormat.format(date));
}
@Test
public void givenGregorianCalendar_whenCustomizedDateFormatSymbols_thenChangedDayNames() {
GregorianCalendar gregorianCalendar = new GregorianCalendar(2018, 1, 1, 10, 15, 20);
Date date = gregorianCalendar.getTime();
Locale.setDefault(new Locale("pl", "PL"));
DateFormatSymbols dateFormatSymbols = new DateFormatSymbols();
dateFormatSymbols.setWeekdays(new String[]{"A", "B", "C", "D", "E", "F", "G", "H"});
SimpleDateFormat standardDateFormat = new SimpleDateFormat("EEEE-MMMM-yyyy HH:mm:ss:SSS");
SimpleDateFormat newDaysDateFormat = new SimpleDateFormat("EEEE-MMMM-yyyy HH:mm:ss:SSS", dateFormatSymbols);
Assert.assertEquals("czwartek-lutego-2018 10:15:20:000", standardDateFormat.format(date));
Assert.assertEquals("F-lutego-2018 10:15:20:000", newDaysDateFormat.format(date));
}
}

View File

@@ -0,0 +1,76 @@
package com.baeldung.internationalization;
import org.junit.Assert;
import org.junit.Test;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.Currency;
import java.util.Locale;
public class NumbersCurrenciesFormattingUnitTest {
@Test
public void givenDifferentLocalesAndDoubleNumber_whenNumberInstance_thenDifferentOutput() {
Locale usLocale = Locale.US;
Locale plLocale = new Locale("pl", "PL");
Locale deLocale = Locale.GERMANY;
double number = 102_300.456d;
NumberFormat usNumberFormat = NumberFormat.getInstance(usLocale);
NumberFormat plNumberFormat = NumberFormat.getInstance(plLocale);
NumberFormat deNumberFormat = NumberFormat.getInstance(deLocale);
Assert.assertEquals(usNumberFormat.format(number), "102,300.456");
Assert.assertEquals(plNumberFormat.format(number), "102 300,456");
Assert.assertEquals(deNumberFormat.format(number), "102.300,456");
}
@Test
public void givenDifferentLocalesAndDoubleAmount_whenCurrencyInstance_thenDifferentOutput() {
Locale usLocale = Locale.US;
Locale plLocale = new Locale("pl", "PL");
Locale deLocale = Locale.GERMANY;
BigDecimal number = new BigDecimal(102_300.456d);
NumberFormat usNumberFormat = NumberFormat.getCurrencyInstance(usLocale);
NumberFormat plNumberFormat = NumberFormat.getCurrencyInstance(plLocale);
NumberFormat deNumberFormat = NumberFormat.getCurrencyInstance(deLocale);
Assert.assertEquals(usNumberFormat.format(number), "$102,300.46");
Assert.assertEquals(plNumberFormat.format(number), "102 300,46 zł");
Assert.assertEquals(deNumberFormat.format(number), "102.300,46 €");
}
@Test
public void givenLocaleAndNumber_whenSpecificDecimalFormat_thenSpecificOutput() {
Locale.setDefault(Locale.FRANCE);
BigDecimal number = new BigDecimal(102_300.456d);
DecimalFormat zeroDecimalFormat = new DecimalFormat("000000000.0000");
DecimalFormat hashDecimalFormat = new DecimalFormat("###,###.#");
DecimalFormat dollarDecimalFormat = new DecimalFormat("$###,###.##");
Assert.assertEquals(zeroDecimalFormat.format(number), "000102300,4560");
Assert.assertEquals(hashDecimalFormat.format(number), "102 300,5");
Assert.assertEquals(dollarDecimalFormat.format(number), "$102 300,46");
}
@Test
public void givenLocaleAndNumber_whenSpecificDecimalFormatSymbols_thenSpecificOutput() {
Locale.setDefault(Locale.FRANCE);
BigDecimal number = new BigDecimal(102_300.456d);
DecimalFormatSymbols decimalFormatSymbols = DecimalFormatSymbols.getInstance();
decimalFormatSymbols.setGroupingSeparator('^');
decimalFormatSymbols.setDecimalSeparator('@');
DecimalFormat separatorsDecimalFormat = new DecimalFormat("$###,###.##");
separatorsDecimalFormat.setGroupingSize(4);
separatorsDecimalFormat.setCurrency(Currency.getInstance(Locale.JAPAN));
separatorsDecimalFormat.setDecimalFormatSymbols(decimalFormatSymbols);
Assert.assertEquals(separatorsDecimalFormat.format(number), "$10^2300@46");
}
}

View File

@@ -0,0 +1,27 @@
package com.baeldung.java8;
import com.baeldung.java_8_features.Vehicle;
import com.baeldung.java_8_features.VehicleImpl;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class Java8DefaultStaticIntefaceMethodsUnitTest {
@Test
public void callStaticInterfaceMethdosMethods_whenExpectedResults_thenCorrect() {
Vehicle vehicle = new VehicleImpl();
String overview = vehicle.getOverview();
long[] startPosition = vehicle.startPosition();
assertEquals(overview, "ATV made by N&F Vehicles");
assertEquals(startPosition[0], 23);
assertEquals(startPosition[1], 15);
}
@Test
public void callDefaultInterfaceMethods_whenExpectedResults_thenCorrect() {
String producer = Vehicle.producer();
assertEquals(producer, "N&F Vehicles");
}
}

View File

@@ -0,0 +1,111 @@
package com.baeldung.java8;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.function.Consumer;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Java8ForEachUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(Java8ForEachUnitTest.class);
@Test
public void compareForEachMethods_thenPrintResults() {
List<String> names = new ArrayList<>();
names.add("Larry");
names.add("Steve");
names.add("James");
names.add("Conan");
names.add("Ellen");
// Java 5 - for-loop
LOG.debug("--- Enhanced for-loop ---");
for (String name : names) {
LOG.debug(name);
}
// Java 8 - forEach
names.forEach(name -> {
System.out.println(name);
});
LOG.debug("--- Print Consumer ---");
Consumer<String> printConsumer = new Consumer<String>() {
public void accept(String name) {
System.out.println(name);
};
};
names.forEach(printConsumer);
// Anonymous inner class that implements Consumer interface
LOG.debug("--- Anonymous inner class ---");
names.forEach(new Consumer<String>() {
public void accept(String name) {
LOG.debug(name);
}
});
// Java 8 - forEach - Lambda Syntax
LOG.debug("--- forEach method ---");
names.forEach(name -> LOG.debug(name));
// Java 8 - forEach - Print elements using a Method Reference
LOG.debug("--- Method Reference ---");
names.forEach(LOG::debug);
}
@Test
public void givenList_thenIterateAndPrintResults() {
List<String> names = Arrays.asList("Larry", "Steve", "James");
names.forEach(System.out::println);
}
@Test
public void givenSet_thenIterateAndPrintResults() {
Set<String> uniqueNames = new HashSet<>(Arrays.asList("Larry", "Steve", "James"));
uniqueNames.forEach(System.out::println);
}
@Test
public void givenQueue_thenIterateAndPrintResults() {
Queue<String> namesQueue = new ArrayDeque<>(Arrays.asList("Larry", "Steve", "James"));
namesQueue.forEach(System.out::println);
}
@Test
public void givenMap_thenIterateAndPrintResults() {
Map<Integer, String> namesMap = new HashMap<>();
namesMap.put(1, "Larry");
namesMap.put(2, "Steve");
namesMap.put(3, "James");
namesMap.entrySet()
.forEach(entry -> System.out.println(entry.getKey() + " " + entry.getValue()));
}
@Test
public void givenMap_whenUsingBiConsumer_thenIterateAndPrintResults2() {
Map<Integer, String> namesMap = new HashMap<>();
namesMap.put(1, "Larry");
namesMap.put(2, "Steve");
namesMap.put(3, "James");
namesMap.forEach((key, value) -> System.out.println(key + " " + value));
}
}

View File

@@ -0,0 +1,183 @@
package com.baeldung.java8;
import com.baeldung.java_8_features.groupingby.BlogPost;
import com.baeldung.java_8_features.groupingby.BlogPostType;
import org.junit.Test;
import java.util.*;
import java.util.concurrent.ConcurrentMap;
import static java.util.Comparator.comparingInt;
import static java.util.stream.Collectors.*;
import static org.junit.Assert.*;
public class Java8GroupingByCollectorUnitTest {
private static final List<BlogPost> posts = Arrays.asList(new BlogPost("News item 1", "Author 1", BlogPostType.NEWS, 15), new BlogPost("Tech review 1", "Author 2", BlogPostType.REVIEW, 5),
new BlogPost("Programming guide", "Author 1", BlogPostType.GUIDE, 20), new BlogPost("News item 2", "Author 2", BlogPostType.NEWS, 35), new BlogPost("Tech review 2", "Author 1", BlogPostType.REVIEW, 15));
@Test
public void givenAListOfPosts_whenGroupedByType_thenGetAMapBetweenTypeAndPosts() {
Map<BlogPostType, List<BlogPost>> postsPerType = posts.stream()
.collect(groupingBy(BlogPost::getType));
assertEquals(2, postsPerType.get(BlogPostType.NEWS)
.size());
assertEquals(1, postsPerType.get(BlogPostType.GUIDE)
.size());
assertEquals(2, postsPerType.get(BlogPostType.REVIEW)
.size());
}
@Test
public void givenAListOfPosts_whenGroupedByTypeAndTheirTitlesAreJoinedInAString_thenGetAMapBetweenTypeAndCsvTitles() {
Map<BlogPostType, String> postsPerType = posts.stream()
.collect(groupingBy(BlogPost::getType, mapping(BlogPost::getTitle, joining(", ", "Post titles: [", "]"))));
assertEquals("Post titles: [News item 1, News item 2]", postsPerType.get(BlogPostType.NEWS));
assertEquals("Post titles: [Programming guide]", postsPerType.get(BlogPostType.GUIDE));
assertEquals("Post titles: [Tech review 1, Tech review 2]", postsPerType.get(BlogPostType.REVIEW));
}
@Test
public void givenAListOfPosts_whenGroupedByTypeAndSumTheLikes_thenGetAMapBetweenTypeAndPostLikes() {
Map<BlogPostType, Integer> likesPerType = posts.stream()
.collect(groupingBy(BlogPost::getType, summingInt(BlogPost::getLikes)));
assertEquals(50, likesPerType.get(BlogPostType.NEWS)
.intValue());
assertEquals(20, likesPerType.get(BlogPostType.REVIEW)
.intValue());
assertEquals(20, likesPerType.get(BlogPostType.GUIDE)
.intValue());
}
@Test
public void givenAListOfPosts_whenGroupedByTypeInAnEnumMap_thenGetAnEnumMapBetweenTypeAndPosts() {
EnumMap<BlogPostType, List<BlogPost>> postsPerType = posts.stream()
.collect(groupingBy(BlogPost::getType, () -> new EnumMap<>(BlogPostType.class), toList()));
assertEquals(2, postsPerType.get(BlogPostType.NEWS)
.size());
assertEquals(1, postsPerType.get(BlogPostType.GUIDE)
.size());
assertEquals(2, postsPerType.get(BlogPostType.REVIEW)
.size());
}
@Test
public void givenAListOfPosts_whenGroupedByTypeInSets_thenGetAMapBetweenTypesAndSetsOfPosts() {
Map<BlogPostType, Set<BlogPost>> postsPerType = posts.stream()
.collect(groupingBy(BlogPost::getType, toSet()));
assertEquals(2, postsPerType.get(BlogPostType.NEWS)
.size());
assertEquals(1, postsPerType.get(BlogPostType.GUIDE)
.size());
assertEquals(2, postsPerType.get(BlogPostType.REVIEW)
.size());
}
@Test
public void givenAListOfPosts_whenGroupedByTypeConcurrently_thenGetAMapBetweenTypeAndPosts() {
ConcurrentMap<BlogPostType, List<BlogPost>> postsPerType = posts.parallelStream()
.collect(groupingByConcurrent(BlogPost::getType));
assertEquals(2, postsPerType.get(BlogPostType.NEWS)
.size());
assertEquals(1, postsPerType.get(BlogPostType.GUIDE)
.size());
assertEquals(2, postsPerType.get(BlogPostType.REVIEW)
.size());
}
@Test
public void givenAListOfPosts_whenGroupedByTypeAndAveragingLikes_thenGetAMapBetweenTypeAndAverageNumberOfLikes() {
Map<BlogPostType, Double> averageLikesPerType = posts.stream()
.collect(groupingBy(BlogPost::getType, averagingInt(BlogPost::getLikes)));
assertEquals(25, averageLikesPerType.get(BlogPostType.NEWS)
.intValue());
assertEquals(20, averageLikesPerType.get(BlogPostType.GUIDE)
.intValue());
assertEquals(10, averageLikesPerType.get(BlogPostType.REVIEW)
.intValue());
}
@Test
public void givenAListOfPosts_whenGroupedByTypeAndCounted_thenGetAMapBetweenTypeAndNumberOfPosts() {
Map<BlogPostType, Long> numberOfPostsPerType = posts.stream()
.collect(groupingBy(BlogPost::getType, counting()));
assertEquals(2, numberOfPostsPerType.get(BlogPostType.NEWS)
.intValue());
assertEquals(1, numberOfPostsPerType.get(BlogPostType.GUIDE)
.intValue());
assertEquals(2, numberOfPostsPerType.get(BlogPostType.REVIEW)
.intValue());
}
@Test
public void givenAListOfPosts_whenGroupedByTypeAndMaxingLikes_thenGetAMapBetweenTypeAndMaximumNumberOfLikes() {
Map<BlogPostType, Optional<BlogPost>> maxLikesPerPostType = posts.stream()
.collect(groupingBy(BlogPost::getType, maxBy(comparingInt(BlogPost::getLikes))));
assertTrue(maxLikesPerPostType.get(BlogPostType.NEWS)
.isPresent());
assertEquals(35, maxLikesPerPostType.get(BlogPostType.NEWS)
.get()
.getLikes());
assertTrue(maxLikesPerPostType.get(BlogPostType.GUIDE)
.isPresent());
assertEquals(20, maxLikesPerPostType.get(BlogPostType.GUIDE)
.get()
.getLikes());
assertTrue(maxLikesPerPostType.get(BlogPostType.REVIEW)
.isPresent());
assertEquals(15, maxLikesPerPostType.get(BlogPostType.REVIEW)
.get()
.getLikes());
}
@Test
public void givenAListOfPosts_whenGroupedByAuthorAndThenByType_thenGetAMapBetweenAuthorAndMapsBetweenTypeAndBlogPosts() {
Map<String, Map<BlogPostType, List<BlogPost>>> map = posts.stream()
.collect(groupingBy(BlogPost::getAuthor, groupingBy(BlogPost::getType)));
assertEquals(1, map.get("Author 1")
.get(BlogPostType.NEWS)
.size());
assertEquals(1, map.get("Author 1")
.get(BlogPostType.GUIDE)
.size());
assertEquals(1, map.get("Author 1")
.get(BlogPostType.REVIEW)
.size());
assertEquals(1, map.get("Author 2")
.get(BlogPostType.NEWS)
.size());
assertEquals(1, map.get("Author 2")
.get(BlogPostType.REVIEW)
.size());
assertNull(map.get("Author 2")
.get(BlogPostType.GUIDE));
}
@Test
public void givenAListOfPosts_whenGroupedByTypeAndSummarizingLikes_thenGetAMapBetweenTypeAndSummary() {
Map<BlogPostType, IntSummaryStatistics> likeStatisticsPerType = posts.stream()
.collect(groupingBy(BlogPost::getType, summarizingInt(BlogPost::getLikes)));
IntSummaryStatistics newsLikeStatistics = likeStatisticsPerType.get(BlogPostType.NEWS);
assertEquals(2, newsLikeStatistics.getCount());
assertEquals(50, newsLikeStatistics.getSum());
assertEquals(25.0, newsLikeStatistics.getAverage(), 0.001);
assertEquals(35, newsLikeStatistics.getMax());
assertEquals(15, newsLikeStatistics.getMin());
}
}

View File

@@ -0,0 +1,67 @@
package com.baeldung.java8;
import com.baeldung.java_8_features.User;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class Java8MethodReferenceUnitTest {
private List<String> list;
@Before
public void init() {
list = new ArrayList<>();
list.add("One");
list.add("OneAndOnly");
list.add("Derek");
list.add("Change");
list.add("factory");
list.add("justBefore");
list.add("Italy");
list.add("Italy");
list.add("Thursday");
list.add("");
list.add("");
}
@Test
public void checkStaticMethodReferences_whenWork_thenCorrect() {
List<User> users = new ArrayList<>();
users.add(new User());
users.add(new User());
boolean isReal = users.stream().anyMatch(u -> User.isRealUser(u));
boolean isRealRef = users.stream().anyMatch(User::isRealUser);
assertTrue(isReal);
assertTrue(isRealRef);
}
@Test
public void checkInstanceMethodReferences_whenWork_thenCorrect() {
User user = new User();
boolean isLegalName = list.stream().anyMatch(user::isLegalName);
assertTrue(isLegalName);
}
@Test
public void checkParticularTypeReferences_whenWork_thenCorrect() {
long count = list.stream().filter(String::isEmpty).count();
assertEquals(count, 2);
}
@Test
public void checkConstructorReferences_whenWork_thenCorrect() {
Stream<User> stream = list.stream().map(User::new);
List<User> userList = stream.collect(Collectors.toList());
assertEquals(userList.size(), list.size());
assertTrue(userList.get(0) instanceof User);
}
}

View File

@@ -0,0 +1,116 @@
package com.baeldung.java8;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.java_8_features.Address;
import com.baeldung.java_8_features.CustomException;
import com.baeldung.java_8_features.OptionalAddress;
import com.baeldung.java_8_features.OptionalUser;
import com.baeldung.java_8_features.User;
public class Java8OptionalUnitTest {
private List<String> list;
@Before
public void init() {
list = new ArrayList<>();
list.add("One");
list.add("OneAndOnly");
list.add("Derek");
list.add("Change");
list.add("factory");
list.add("justBefore");
list.add("Italy");
list.add("Italy");
list.add("Thursday");
list.add("");
list.add("");
}
@Test
public void checkOptional_whenAsExpected_thenCorrect() {
Optional<String> optionalEmpty = Optional.empty();
assertFalse(optionalEmpty.isPresent());
String str = "value";
Optional<String> optional = Optional.of(str);
assertEquals(optional.get(), "value");
Optional<String> optionalNullable = Optional.ofNullable(str);
Optional<String> optionalNull = Optional.ofNullable(null);
assertEquals(optionalNullable.get(), "value");
assertFalse(optionalNull.isPresent());
List<String> listOpt = Optional.of(list).orElse(new ArrayList<>());
List<String> listNull = null;
List<String> listOptNull = Optional.ofNullable(listNull).orElse(new ArrayList<>());
assertTrue(listOpt == list);
assertTrue(listOptNull.isEmpty());
Optional<User> user = Optional.ofNullable(getUser());
String result = user.map(User::getAddress).map(Address::getStreet).orElse("not specified");
assertEquals(result, "1st Avenue");
Optional<OptionalUser> optionalUser = Optional.ofNullable(getOptionalUser());
String resultOpt = optionalUser.flatMap(OptionalUser::getAddress).flatMap(OptionalAddress::getStreet).orElse("not specified");
assertEquals(resultOpt, "1st Avenue");
Optional<User> userNull = Optional.ofNullable(getUserNull());
String resultNull = userNull.map(User::getAddress).map(Address::getStreet).orElse("not specified");
assertEquals(resultNull, "not specified");
Optional<OptionalUser> optionalUserNull = Optional.ofNullable(getOptionalUserNull());
String resultOptNull = optionalUserNull.flatMap(OptionalUser::getAddress).flatMap(OptionalAddress::getStreet).orElse("not specified");
assertEquals(resultOptNull, "not specified");
}
@Test(expected = CustomException.class)
public void callMethod_whenCustomException_thenCorrect() {
User user = new User();
String result = user.getOrThrow();
}
private User getUser() {
User user = new User();
Address address = new Address();
address.setStreet("1st Avenue");
user.setAddress(address);
return user;
}
private OptionalUser getOptionalUser() {
OptionalUser user = new OptionalUser();
OptionalAddress address = new OptionalAddress();
address.setStreet("1st Avenue");
user.setAddress(address);
return user;
}
private OptionalUser getOptionalUserNull() {
OptionalUser user = new OptionalUser();
OptionalAddress address = new OptionalAddress();
address.setStreet(null);
user.setAddress(address);
return user;
}
private User getUserNull() {
User user = new User();
Address address = new Address();
address.setStreet(null);
user.setAddress(address);
return user;
}
}

View File

@@ -0,0 +1,131 @@
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

@@ -0,0 +1,167 @@
package com.baeldung.java8;
import static org.hamcrest.Matchers.equalTo;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.Assert;
import org.junit.Test;
import com.baeldung.java8.entity.Human;
import com.google.common.collect.Lists;
import com.google.common.primitives.Ints;
public class Java8SortUnitTest {
// tests -
@Test
public final void givenPreLambda_whenSortingEntitiesByName_thenCorrectlySorted() {
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
Collections.sort(humans, new Comparator<Human>() {
@Override
public final int compare(final Human h1, final Human h2) {
return h1.getName().compareTo(h2.getName());
}
});
Assert.assertThat(humans.get(0), equalTo(new Human("Jack", 12)));
}
@Test
public final void whenSortingEntitiesByName_thenCorrectlySorted() {
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
humans.sort((final Human h1, final Human h2) -> h1.getName().compareTo(h2.getName()));
Assert.assertThat(humans.get(0), equalTo(new Human("Jack", 12)));
}
@Test
public final void givenLambdaShortForm_whenSortingEntitiesByName_thenCorrectlySorted() {
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
humans.sort((h1, h2) -> h1.getName().compareTo(h2.getName()));
Assert.assertThat(humans.get(0), equalTo(new Human("Jack", 12)));
}
@Test
public final void whenSortingEntitiesByNameThenAge_thenCorrectlySorted() {
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 12), new Human("Sarah", 10), new Human("Zack", 12));
humans.sort((lhs, rhs) -> {
if (lhs.getName().equals(rhs.getName())) {
return lhs.getAge() - rhs.getAge();
} else {
return lhs.getName().compareTo(rhs.getName());
}
});
Assert.assertThat(humans.get(0), equalTo(new Human("Sarah", 10)));
}
@Test
public final void givenCompositionVerbose_whenSortingEntitiesByNameThenAge_thenCorrectlySorted() {
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 12), new Human("Sarah", 10), new Human("Zack", 12));
final Comparator<Human> byName = (h1, h2) -> h1.getName().compareTo(h2.getName());
final Comparator<Human> byAge = (h1, h2) -> Ints.compare(h1.getAge(), h2.getAge());
humans.sort(byName.thenComparing(byAge));
Assert.assertThat(humans.get(0), equalTo(new Human("Sarah", 10)));
}
@Test
public final void givenComposition_whenSortingEntitiesByNameThenAge_thenCorrectlySorted() {
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 12), new Human("Sarah", 10), new Human("Zack", 12));
humans.sort(Comparator.comparing(Human::getName).thenComparing(Human::getAge));
Assert.assertThat(humans.get(0), equalTo(new Human("Sarah", 10)));
}
@Test
public final void whenSortingEntitiesByAge_thenCorrectlySorted() {
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
humans.sort((h1, h2) -> Ints.compare(h1.getAge(), h2.getAge()));
Assert.assertThat(humans.get(0), equalTo(new Human("Sarah", 10)));
}
@Test
public final void whenSortingEntitiesByNameReversed_thenCorrectlySorted() {
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
final Comparator<Human> comparator = (h1, h2) -> h1.getName().compareTo(h2.getName());
humans.sort(comparator.reversed());
Assert.assertThat(humans.get(0), equalTo(new Human("Sarah", 10)));
}
@Test
public final void givenMethodDefinition_whenSortingEntitiesByNameThenAge_thenCorrectlySorted() {
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
humans.sort(Human::compareByNameThenAge);
Assert.assertThat(humans.get(0), equalTo(new Human("Jack", 12)));
}
@Test
public final void givenInstanceMethod_whenSortingEntitiesByName_thenCorrectlySorted() {
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
humans.sort(Comparator.comparing(Human::getName));
Assert.assertThat(humans.get(0), equalTo(new Human("Jack", 12)));
}
@Test
public final void givenStreamNaturalOrdering_whenSortingEntitiesByName_thenCorrectlySorted() {
final List<String> letters = Lists.newArrayList("B", "A", "C");
final List<String> sortedLetters = letters.stream().sorted().collect(Collectors.toList());
Assert.assertThat(sortedLetters.get(0), equalTo("A"));
}
@Test
public final void givenStreamCustomOrdering_whenSortingEntitiesByName_thenCorrectlySorted() {
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
final Comparator<Human> nameComparator = (h1, h2) -> h1.getName().compareTo(h2.getName());
final List<Human> sortedHumans = humans.stream().sorted(nameComparator).collect(Collectors.toList());
Assert.assertThat(sortedHumans.get(0), equalTo(new Human("Jack", 12)));
}
@Test
public final void givenStreamComparatorOrdering_whenSortingEntitiesByName_thenCorrectlySorted() {
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
final List<Human> sortedHumans = humans.stream().sorted(Comparator.comparing(Human::getName)).collect(Collectors.toList());
Assert.assertThat(sortedHumans.get(0), equalTo(new Human("Jack", 12)));
}
@Test
public final void givenStreamNaturalOrdering_whenSortingEntitiesByNameReversed_thenCorrectlySorted() {
final List<String> letters = Lists.newArrayList("B", "A", "C");
final List<String> reverseSortedLetters = letters.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
Assert.assertThat(reverseSortedLetters.get(0), equalTo("C"));
}
@Test
public final void givenStreamCustomOrdering_whenSortingEntitiesByNameReversed_thenCorrectlySorted() {
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
final Comparator<Human> reverseNameComparator = (h1, h2) -> h2.getName().compareTo(h1.getName());
final List<Human> reverseSortedHumans = humans.stream().sorted(reverseNameComparator).collect(Collectors.toList());
Assert.assertThat(reverseSortedHumans.get(0), equalTo(new Human("Sarah", 10)));
}
@Test
public final void givenStreamComparatorOrdering_whenSortingEntitiesByNameReversed_thenCorrectlySorted() {
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
final List<Human> reverseSortedHumans = humans.stream().sorted(Comparator.comparing(Human::getName, Comparator.reverseOrder())).collect(Collectors.toList());
Assert.assertThat(reverseSortedHumans.get(0), equalTo(new Human("Sarah", 10)));
}
}

View File

@@ -0,0 +1,92 @@
package com.baeldung.java8;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import java.util.Scanner;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class JavaTryWithResourcesLongRunningUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(JavaTryWithResourcesLongRunningUnitTest.class);
private static final String TEST_STRING_HELLO_WORLD = "Hello World";
private Date resource1Date, resource2Date;
// tests
/* Example for using Try_with_resources */
@Test
public void whenWritingToStringWriter_thenCorrectlyWritten() {
final StringWriter sw = new StringWriter();
try (PrintWriter pw = new PrintWriter(sw, true)) {
pw.print(TEST_STRING_HELLO_WORLD);
}
Assert.assertEquals(sw.getBuffer()
.toString(), TEST_STRING_HELLO_WORLD);
}
/* Example for using multiple resources */
@Test
public void givenStringToScanner_whenWritingToStringWriter_thenCorrectlyWritten() {
final StringWriter sw = new StringWriter();
try (Scanner sc = new Scanner(TEST_STRING_HELLO_WORLD); PrintWriter pw = new PrintWriter(sw, true)) {
while (sc.hasNext()) {
pw.print(sc.nextLine());
}
}
Assert.assertEquals(sw.getBuffer()
.toString(), TEST_STRING_HELLO_WORLD);
}
/* Example to show order in which the resources are closed */
@Test
public void whenFirstAutoClosableResourceIsinitializedFirst_thenFirstAutoClosableResourceIsReleasedFirst() throws Exception {
try (AutoCloseableResourcesFirst af = new AutoCloseableResourcesFirst(); AutoCloseableResourcesSecond as = new AutoCloseableResourcesSecond()) {
af.doSomething();
as.doSomething();
}
Assert.assertTrue(resource1Date.after(resource2Date));
}
class AutoCloseableResourcesFirst implements AutoCloseable {
public AutoCloseableResourcesFirst() {
LOG.debug("Constructor -> AutoCloseableResources_First");
}
public void doSomething() {
LOG.debug("Something -> AutoCloseableResources_First");
}
@Override
public void close() throws Exception {
LOG.debug("Closed AutoCloseableResources_First");
resource1Date = new Date();
}
}
class AutoCloseableResourcesSecond implements AutoCloseable {
public AutoCloseableResourcesSecond() {
LOG.debug("Constructor -> AutoCloseableResources_Second");
}
public void doSomething() {
LOG.debug("Something -> AutoCloseableResources_Second");
}
@Override
public void close() throws Exception {
LOG.debug("Closed AutoCloseableResources_Second");
resource2Date = new Date();
Thread.sleep(10000);
}
}
}

View File

@@ -0,0 +1,60 @@
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

@@ -0,0 +1,22 @@
package com.baeldung.java8.comparator;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
@Data
@AllArgsConstructor
@ToString
@EqualsAndHashCode
public class Employee implements Comparable<Employee>{
String name;
int age;
double salary;
long mobile;
@Override
public int compareTo(Employee argEmployee) {
return name.compareTo(argEmployee.getName());
}
}

View File

@@ -0,0 +1,152 @@
package com.baeldung.java8.comparator;
import java.util.Arrays;
import java.util.Comparator;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class Java8ComparatorUnitTest {
private Employee[] employees;
private Employee[] employeesArrayWithNulls;
private Employee[] sortedEmployeesByName;
private Employee[] sortedEmployeesByNameDesc;
private Employee[] sortedEmployeesByAge;
private Employee[] sortedEmployeesByMobile;
private Employee[] sortedEmployeesBySalary;
private Employee[] sortedEmployeesArray_WithNullsFirst;
private Employee[] sortedEmployeesArray_WithNullsLast;
private Employee[] sortedEmployeesByNameAge;
private Employee[] someMoreEmployees;
private Employee[] sortedEmployeesByAgeName;;
@Before
public void initData() {
employees = new Employee[] { new Employee("John", 25, 3000, 9922001), new Employee("Ace", 22, 2000, 5924001), new Employee("Keith", 35, 4000, 3924401) };
employeesArrayWithNulls = new Employee[] { new Employee("John", 25, 3000, 9922001), null, new Employee("Ace", 22, 2000, 5924001), null, new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesByName = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesByNameDesc = new Employee[] { new Employee("Keith", 35, 4000, 3924401), new Employee("John", 25, 3000, 9922001), new Employee("Ace", 22, 2000, 5924001) };
sortedEmployeesByAge = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesByMobile = new Employee[] { new Employee("Keith", 35, 4000, 3924401), new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), };
sortedEmployeesBySalary = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401), };
sortedEmployeesArray_WithNullsFirst = new Employee[] { null, null, new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesArray_WithNullsLast = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401), null, null };
someMoreEmployees = new Employee[] { new Employee("Jake", 25, 3000, 9922001), new Employee("Jake", 22, 2000, 5924001), new Employee("Ace", 22, 3000, 6423001), new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesByAgeName = new Employee[] { new Employee("Ace", 22, 3000, 6423001), new Employee("Jake", 22, 2000, 5924001), new Employee("Jake", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
sortedEmployeesByNameAge = new Employee[] { new Employee("Ace", 22, 3000, 6423001), new Employee("Jake", 22, 2000, 5924001), new Employee("Jake", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
}
@Test
public void whenComparing_thenSortedByName() {
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
Arrays.sort(employees, employeeNameComparator);
// System.out.println(Arrays.toString(employees));
assertTrue(Arrays.equals(employees, sortedEmployeesByName));
}
@Test
public void whenComparingWithComparator_thenSortedByNameDesc() {
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName, (s1, s2) -> {
return s2.compareTo(s1);
});
Arrays.sort(employees, employeeNameComparator);
// System.out.println(Arrays.toString(employees));
assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc));
}
@Test
public void whenReversed_thenSortedByNameDesc() {
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
Comparator<Employee> employeeNameComparatorReversed = employeeNameComparator.reversed();
Arrays.sort(employees, employeeNameComparatorReversed);
// System.out.println(Arrays.toString(employees));
assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc));
}
@Test
public void whenComparingInt_thenSortedByAge() {
Comparator<Employee> employeeAgeComparator = Comparator.comparingInt(Employee::getAge);
Arrays.sort(employees, employeeAgeComparator);
// System.out.println(Arrays.toString(employees));
assertTrue(Arrays.equals(employees, sortedEmployeesByAge));
}
@Test
public void whenComparingLong_thenSortedByMobile() {
Comparator<Employee> employeeMobileComparator = Comparator.comparingLong(Employee::getMobile);
Arrays.sort(employees, employeeMobileComparator);
// System.out.println(Arrays.toString(employees));
assertTrue(Arrays.equals(employees, sortedEmployeesByMobile));
}
@Test
public void whenComparingDouble_thenSortedBySalary() {
Comparator<Employee> employeeSalaryComparator = Comparator.comparingDouble(Employee::getSalary);
Arrays.sort(employees, employeeSalaryComparator);
// System.out.println(Arrays.toString(employees));
assertTrue(Arrays.equals(employees, sortedEmployeesBySalary));
}
@Test
public void whenNaturalOrder_thenSortedByName() {
Comparator<Employee> employeeNameComparator = Comparator.<Employee> naturalOrder();
Arrays.sort(employees, employeeNameComparator);
// System.out.println(Arrays.toString(employees));
assertTrue(Arrays.equals(employees, sortedEmployeesByName));
}
@Test
public void whenReverseOrder_thenSortedByNameDesc() {
Comparator<Employee> employeeNameComparator = Comparator.<Employee> reverseOrder();
Arrays.sort(employees, employeeNameComparator);
// System.out.println(Arrays.toString(employees));
assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc));
}
@Test
public void whenNullsFirst_thenSortedByNameWithNullsFirst() {
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
Comparator<Employee> employeeNameComparator_nullFirst = Comparator.nullsFirst(employeeNameComparator);
Arrays.sort(employeesArrayWithNulls, employeeNameComparator_nullFirst);
// System.out.println(Arrays.toString(employeesArrayWithNulls));
assertTrue(Arrays.equals(employeesArrayWithNulls, sortedEmployeesArray_WithNullsFirst));
}
@Test
public void whenNullsLast_thenSortedByNameWithNullsLast() {
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
Comparator<Employee> employeeNameComparator_nullLast = Comparator.nullsLast(employeeNameComparator);
Arrays.sort(employeesArrayWithNulls, employeeNameComparator_nullLast);
// System.out.println(Arrays.toString(employeesArrayWithNulls));
assertTrue(Arrays.equals(employeesArrayWithNulls, sortedEmployeesArray_WithNullsLast));
}
@Test
public void whenThenComparing_thenSortedByAgeName() {
Comparator<Employee> employee_Age_Name_Comparator = Comparator.comparing(Employee::getAge).thenComparing(Employee::getName);
Arrays.sort(someMoreEmployees, employee_Age_Name_Comparator);
// System.out.println(Arrays.toString(someMoreEmployees));
assertTrue(Arrays.equals(someMoreEmployees, sortedEmployeesByAgeName));
}
@Test
public void whenThenComparing_thenSortedByNameAge() {
Comparator<Employee> employee_Name_Age_Comparator = Comparator.comparing(Employee::getName).thenComparingInt(Employee::getAge);
Arrays.sort(someMoreEmployees, employee_Name_Age_Comparator);
// System.out.println(Arrays.toString(someMoreEmployees));
assertTrue(Arrays.equals(someMoreEmployees, sortedEmployeesByNameAge));
}
}

View File

@@ -0,0 +1,89 @@
package com.baeldung.java8.entity;
public class Human {
private String name;
private int age;
public Human() {
super();
}
public Human(final String name, final int age) {
super();
this.name = name;
this.age = age;
}
// API
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(final int age) {
this.age = age;
}
// compare
public static int compareByNameThenAge(final Human lhs, final Human rhs) {
if (lhs.name.equals(rhs.name)) {
return lhs.age - rhs.age;
} else {
return lhs.name.compareTo(rhs.name);
}
}
//
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Human other = (Human) obj;
if (age != other.age) {
return false;
}
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
return true;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Human [name=").append(name).append(", age=").append(age).append("]");
return builder.toString();
}
}

View File

@@ -0,0 +1,50 @@
package com.baeldung.java8.lambda.exceptions;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import static com.baeldung.java8.lambda.exceptions.LambdaExceptionWrappers.*;
public class LambdaExceptionWrappersUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(LambdaExceptionWrappersUnitTest.class);
private List<Integer> integers;
@Before
public void init() {
integers = Arrays.asList(3, 9, 7, 0, 10, 20);
}
@Test
public void whenNoExceptionFromLambdaWrapper_thenSuccess() {
integers.forEach(lambdaWrapper(i -> LOG.debug("{}", 50 / i)));
}
@Test
public void whenNoExceptionFromConsumerWrapper_thenSuccess() {
integers.forEach(consumerWrapper(i -> LOG.debug("{}", 50 / i), ArithmeticException.class));
}
@Test(expected = RuntimeException.class)
public void whenExceptionFromThrowingConsumerWrapper_thenSuccess() {
integers.forEach(throwingConsumerWrapper(i -> writeToFile(i)));
}
@Test
public void whenNoExceptionFromHandlingConsumerWrapper_thenSuccess() {
integers.forEach(handlingConsumerWrapper(i -> writeToFile(i), IOException.class));
}
private void writeToFile(Integer i) throws IOException {
if (i == 0) {
throw new IOException(); // mock IOException
}
}
}

View File

@@ -0,0 +1,34 @@
package com.baeldung.java8.lambda.methodreference;
public class Bicycle {
private String brand;
private Integer frameSize;
public Bicycle(String brand) {
this.brand = brand;
this.frameSize = 0;
}
public Bicycle(String brand, Integer frameSize) {
this.brand = brand;
this.frameSize = frameSize;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public Integer getFrameSize() {
return frameSize;
}
public void setFrameSize(Integer frameSize) {
this.frameSize = frameSize;
}
}

View File

@@ -0,0 +1,13 @@
package com.baeldung.java8.lambda.methodreference;
import java.util.Comparator;
public class BicycleComparator implements Comparator<Bicycle> {
@Override
public int compare(Bicycle a, Bicycle b) {
return a.getFrameSize()
.compareTo(b.getFrameSize());
}
}

View File

@@ -0,0 +1,77 @@
package com.baeldung.java8.lambda.methodreference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.BiFunction;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
public class MethodReferenceUnitTest {
private static <T> void doNothingAtAll(Object... o) {
}
;
@Test
public void referenceToStaticMethod() {
List<String> messages = Arrays.asList("Hello", "Baeldung", "readers!");
messages.forEach(word -> StringUtils.capitalize(word));
messages.forEach(StringUtils::capitalize);
}
@Test
public void referenceToInstanceMethodOfParticularObject() {
BicycleComparator bikeFrameSizeComparator = new BicycleComparator();
createBicyclesList().stream()
.sorted((a, b) -> bikeFrameSizeComparator.compare(a, b));
createBicyclesList().stream()
.sorted(bikeFrameSizeComparator::compare);
}
@Test
public void referenceToInstanceMethodOfArbitratyObjectOfParticularType() {
List<Integer> numbers = Arrays.asList(5, 3, 50, 24, 40, 2, 9, 18);
numbers.stream()
.sorted((a, b) -> Integer.compare(a, b));
numbers.stream()
.sorted(Integer::compare);
}
@Test
public void referenceToConstructor() {
BiFunction<String, Integer, Bicycle> bikeCreator = (brand, frameSize) -> new Bicycle(brand, frameSize);
BiFunction<String, Integer, Bicycle> bikeCreatorMethodReference = Bicycle::new;
List<Bicycle> bikes = new ArrayList<>();
bikes.add(bikeCreator.apply("Giant", 50));
bikes.add(bikeCreator.apply("Scott", 20));
bikes.add(bikeCreatorMethodReference.apply("Trek", 35));
bikes.add(bikeCreatorMethodReference.apply("GT", 40));
}
@Test
public void referenceToConstructorSimpleExample() {
List<String> bikeBrands = Arrays.asList("Giant", "Scott", "Trek", "GT");
bikeBrands.stream()
.map(Bicycle::new)
.toArray(Bicycle[]::new);
}
@Test
public void limitationsAndAdditionalExamples() {
createBicyclesList().forEach(b -> System.out.printf("Bike brand is '%s' and frame size is '%d'%n", b.getBrand(), b.getFrameSize()));
createBicyclesList().forEach((o) -> MethodReferenceUnitTest.doNothingAtAll(o));
}
private List<Bicycle> createBicyclesList() {
List<Bicycle> bikes = new ArrayList<>();
bikes.add(new Bicycle("Giant", 50));
bikes.add(new Bicycle("Scott", 20));
bikes.add(new Bicycle("Trek", 35));
bikes.add(new Bicycle("GT", 40));
return bikes;
}
}

View File

@@ -0,0 +1,94 @@
package com.baeldung.java8.lambda.tips;
import com.baeldung.java8.lambda.tips.Foo;
import com.baeldung.java8.lambda.tips.FooExtended;
import com.baeldung.java8.lambda.tips.UseFoo;
import org.junit.Before;
import org.junit.Test;
import java.util.function.Function;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
public class Java8FunctionalInteracesLambdasUnitTest {
private UseFoo useFoo;
@Before
public void init() {
useFoo = new UseFoo();
}
@Test
public void functionalInterfaceInstantiation_whenReturnDefiniteString_thenCorrect() {
final Foo foo = parameter -> parameter + "from lambda";
final String result = useFoo.add("Message ", foo);
assertEquals("Message from lambda", result);
}
@Test
public void standardFIParameter_whenReturnDefiniteString_thenCorrect() {
final Function<String, String> fn = parameter -> parameter + "from lambda";
final String result = useFoo.addWithStandardFI("Message ", fn);
assertEquals("Message from lambda", result);
}
@Test
public void defaultMethodFromExtendedInterface_whenReturnDefiniteString_thenCorrect() {
final FooExtended fooExtended = string -> string;
final String result = fooExtended.defaultMethod();
assertEquals("String from Bar", result);
}
@Test
public void lambdaAndInnerClassInstantiation_whenReturnSameString_thenCorrect() {
final Foo foo = parameter -> parameter + "from Foo";
final Foo fooByIC = new Foo() {
@Override
public String method(final String string) {
return string + "from Foo";
}
};
assertEquals(foo.method("Something "), fooByIC.method("Something "));
}
@Test
public void accessVariablesFromDifferentScopes_whenReturnPredefinedString_thenCorrect() {
assertEquals("Results: resultIC = Inner class value, resultLambda = Enclosing scope value", useFoo.scopeExperiment());
}
@Test
public void shorteningLambdas_whenReturnEqualsResults_thenCorrect() {
final Foo foo = parameter -> buildString(parameter);
final Foo fooHuge = parameter -> {
final String result = "Something " + parameter;
// many lines of code
return result;
};
assertEquals(foo.method("Something"), fooHuge.method("Something"));
}
private String buildString(final String parameter) {
final String result = "Something " + parameter;
// many lines of code
return result;
}
@Test
public void mutatingOfEffectivelyFinalVariable_whenNotEquals_thenCorrect() {
final int[] total = new int[1];
final Runnable r = () -> total[0]++;
r.run();
assertNotEquals(0, total[0]);
}
}

View File

@@ -0,0 +1,110 @@
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 || input == "" || input == "empty") {
return Optional.empty();
}
return Optional.of(input);
}
}

View File

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

View File

@@ -0,0 +1,44 @@
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

@@ -0,0 +1,89 @@
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

@@ -0,0 +1,41 @@
package com.baeldung.nullsafecollectionstreams;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.stream.Stream;
import org.junit.Test;
import static org.junit.Assert.*;
public class NullSafeCollectionStreamsUsingCommonsEmptyIfNullUnitTest {
private final NullSafeCollectionStreamsUsingCommonsEmptyIfNull instance =
new NullSafeCollectionStreamsUsingCommonsEmptyIfNull();
@Test
public void whenCollectionIsNull_thenExpectAnEmptyStream() {
Collection<String> collection = null;
Stream<String> expResult = Stream.empty();
Stream<String> result = instance.collectionAsStream(collection);
assertStreamEquals(expResult, result);
}
@Test
public void whenCollectionHasElements_thenExpectAStreamOfExactlyTheSameElements() {
Collection<String> collection = Arrays.asList("a", "b", "c");
Stream<String> expResult = Arrays.stream(new String[] { "a", "b", "c" });
Stream<String> result = instance.collectionAsStream(collection);
assertStreamEquals(expResult, result);
}
private static void assertStreamEquals(Stream<?> s1, Stream<?> s2) {
Iterator<?> iter1 = s1.iterator(), iter2 = s2.iterator();
while (iter1.hasNext() && iter2.hasNext())
assertEquals(iter1.next(), iter2.next());
assert !iter1.hasNext() && !iter2.hasNext();
}
}

View File

@@ -0,0 +1,50 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.baeldung.nullsafecollectionstreams;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.stream.Stream;
import org.junit.Test;
/**
*
* @author Kwaje Anthony <kwajeanthony@gmail.com>
*/
public class NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest {
private final NullSafeCollectionStreamsUsingJava8OptionalContainer instance = new NullSafeCollectionStreamsUsingJava8OptionalContainer();
@Test
public void whenCollectionIsNull_thenExpectAnEmptyStream() {
Collection<String> collection = null;
Stream<String> expResult = Stream.empty();
Stream<String> result = instance.collectionAsStream(collection);
assertStreamEquals(expResult, result);
}
@Test
public void whenCollectionHasElements_thenExpectAStreamOfExactlyTheSameElements() {
Collection<String> collection = Arrays.asList("a", "b", "c");
Stream<String> expResult = Arrays.stream(new String[] { "a", "b", "c" });
Stream<String> result = instance.collectionAsStream(collection);
assertStreamEquals(expResult, result);
}
private static void assertStreamEquals(Stream<?> s1, Stream<?> s2) {
Iterator<?> iter1 = s1.iterator(), iter2 = s2.iterator();
while (iter1.hasNext() && iter2.hasNext())
assertEquals(iter1.next(), iter2.next());
assert !iter1.hasNext() && !iter2.hasNext();
}
}

View File

@@ -0,0 +1,45 @@
package com.baeldung.nullsafecollectionstreams;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.stream.Stream;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Kwaje Anthony <kwajeanthony@gmail.com>
*/
public class NullSafeCollectionStreamsUsingNullDereferenceCheckUnitTest {
private final NullSafeCollectionStreamsUsingNullDereferenceCheck instance =
new NullSafeCollectionStreamsUsingNullDereferenceCheck();
@Test
public void whenCollectionIsNull_thenExpectAnEmptyStream() {
Collection<String> collection = null;
Stream<String> expResult = Stream.empty();
Stream<String> result = instance.collectionAsStream(collection);
assertStreamEquals(expResult, result);
}
@Test
public void whenCollectionHasElements_thenExpectAStreamOfExactlyTheSameElements() {
Collection<String> collection = Arrays.asList("a", "b", "c");
Stream<String> expResult = Arrays.stream(new String[] { "a", "b", "c" });
Stream<String> result = instance.collectionAsStream(collection);
assertStreamEquals(expResult, result);
}
private static void assertStreamEquals(Stream<?> s1, Stream<?> s2) {
Iterator<?> iter1 = s1.iterator(), iter2 = s2.iterator();
while (iter1.hasNext() && iter2.hasNext())
assertEquals(iter1.next(), iter2.next());
assert !iter1.hasNext() && !iter2.hasNext();
}
}

View File

@@ -0,0 +1,43 @@
package com.baeldung.optional;
import org.junit.Test;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class PersonRepositoryUnitTest {
PersonRepository personRepository = new PersonRepository();
@Test
public void whenIdIsNull_thenExceptionIsThrown() {
assertThrows(IllegalArgumentException.class,
() ->
Optional
.ofNullable(personRepository.findNameById(null))
.orElseThrow(IllegalArgumentException::new));
}
@Test
public void whenIdIsNonNull_thenNoExceptionIsThrown() {
assertAll(
() ->
Optional
.ofNullable(personRepository.findNameById("id"))
.orElseThrow(RuntimeException::new));
}
@Test
public void whenIdNonNull_thenReturnsNameUpperCase() {
String name = Optional
.ofNullable(personRepository.findNameById("id"))
.map(String::toUpperCase)
.orElseThrow(RuntimeException::new);
assertEquals("NAME", name);
}
}

View File

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

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

View File

@@ -0,0 +1,34 @@
package com.baeldung.reflect;
import static org.assertj.core.api.Assertions.assertThat;
import java.lang.reflect.Parameter;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import org.junit.Test;
public class MethodParamNameUnitTest {
@Test
public void whenGetConstructorParams_thenOk()
throws NoSuchMethodException, SecurityException {
List<Parameter> parameters
= Arrays.asList(Person.class.getConstructor(String.class).getParameters());
Optional<Parameter> parameter
= parameters.stream().filter(Parameter::isNamePresent).findFirst();
assertThat(parameter.get().getName()).isEqualTo("fullName");
}
@Test
public void whenGetMethodParams_thenOk()
throws NoSuchMethodException, SecurityException {
List<Parameter> parameters
= Arrays.asList(
Person.class.getMethod("setFullName", String.class).getParameters());
Optional<Parameter> parameter
= parameters.stream().filter(Parameter::isNamePresent).findFirst();
assertThat(parameter.get().getName()).isEqualTo("fullName");
}
}

View File

@@ -0,0 +1,44 @@
package com.baeldung.spliteratorAPI;
import java.util.Arrays;
import java.util.Spliterator;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import static org.assertj.core.api.Assertions.*;
import org.junit.Before;
import org.junit.Test;
public class ExecutorUnitTest {
Article article;
Stream<Author> stream;
Spliterator<Author> spliterator;
Spliterator<Article> split1;
Spliterator<Article> split2;
@Before
public void init() {
article = new Article(Arrays.asList(new Author("Ahmad", 0), new Author("Eugen", 0), new Author("Alice", 1),
new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0),
new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0),
new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1),
new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1),
new Author("Mike", 0), new Author("Michał", 0), new Author("Loredana", 1)), 0);
stream = article.getListOfAuthors().stream();
split1 = Executor.generateElements().spliterator();
split2 = split1.trySplit();
spliterator = new RelatedAuthorSpliterator(article.getListOfAuthors());
}
@Test
public void givenAstreamOfAuthors_whenProcessedInParallelWithCustomSpliterator_coubtProducessRightOutput() {
Stream<Author> stream2 = StreamSupport.stream(spliterator, true);
assertThat(Executor.countAutors(stream2.parallel())).isEqualTo(9);
}
@Test
public void givenSpliterator_whenAppliedToAListOfArticle_thenSplittedInHalf() {
assertThat(new Task(split1).call()).containsSequence(Executor.generateElements().size() / 2 + "");
assertThat(new Task(split2).call()).containsSequence(Executor.generateElements().size() / 2 + "");
}
}

View File

@@ -0,0 +1,75 @@
package com.baeldung.strategy;
import org.junit.Test;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import static com.baeldung.strategy.Discounter.christmas;
import static com.baeldung.strategy.Discounter.easter;
import static com.baeldung.strategy.Discounter.newYear;
import static org.assertj.core.api.Assertions.assertThat;
public class StrategyDesignPatternUnitTest {
@Test
public void shouldDivideByTwo_WhenApplyingStaffDiscounter() {
Discounter staffDiscounter = new EasterDiscounter();
final BigDecimal discountedValue = staffDiscounter
.apply(BigDecimal.valueOf(100));
assertThat(discountedValue)
.isEqualByComparingTo(BigDecimal.valueOf(50));
}
@Test
public void shouldDivideByTwo_WhenApplyingStaffDiscounterWithAnonyousTypes() {
Discounter staffDiscounter = new Discounter() {
@Override
public BigDecimal apply(BigDecimal amount) {
return amount.multiply(BigDecimal.valueOf(0.5));
}
};
final BigDecimal discountedValue = staffDiscounter
.apply(BigDecimal.valueOf(100));
assertThat(discountedValue)
.isEqualByComparingTo(BigDecimal.valueOf(50));
}
@Test
public void shouldDivideByTwo_WhenApplyingStaffDiscounterWithLamda() {
Discounter staffDiscounter = amount -> amount.multiply(BigDecimal.valueOf(0.5));
final BigDecimal discountedValue = staffDiscounter
.apply(BigDecimal.valueOf(100));
assertThat(discountedValue)
.isEqualByComparingTo(BigDecimal.valueOf(50));
}
@Test
public void shouldApplyAllDiscounts() {
List<Discounter> discounters = Arrays.asList(christmas(), newYear(), easter());
BigDecimal amount = BigDecimal.valueOf(100);
final Discounter combinedDiscounter = discounters
.stream()
.reduce(v -> v, Discounter::combine);
combinedDiscounter.apply(amount);
}
@Test
public void shouldChainDiscounters() {
final Function<BigDecimal, BigDecimal> combinedDiscounters = Discounter
.christmas()
.andThen(newYear());
combinedDiscounters.apply(BigDecimal.valueOf(100));
}
}

View File

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

@@ -0,0 +1,126 @@
package com.baeldung.streamreduce.tests;
import com.baeldung.streamreduce.entities.User;
import com.baeldung.streamreduce.utilities.NumberUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class StreamReduceManualTest {
@Test
public void givenIntegerList_whenReduceWithSumAccumulatorLambda_thenCorrect() {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
int result = numbers.stream().reduce(0, (a, b) -> a + b);
assertThat(result).isEqualTo(21);
}
@Test
public void givenIntegerList_whenReduceWithSumAccumulatorMethodReference_thenCorrect() {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
int result = numbers.stream().reduce(0, Integer::sum);
assertThat(result).isEqualTo(21);
}
@Test
public void givenStringList_whenReduceWithConcatenatorAccumulatorLambda_thenCorrect() {
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
String result = letters.stream().reduce("", (a, b) -> a + b);
assertThat(result).isEqualTo("abcde");
}
@Test
public void givenStringList_whenReduceWithConcatenatorAccumulatorMethodReference_thenCorrect() {
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
String result = letters.stream().reduce("", String::concat);
assertThat(result).isEqualTo("abcde");
}
@Test
public void givenStringList_whenReduceWithUppercaseConcatenatorAccumulator_thenCorrect() {
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
String result = letters.stream().reduce("", (a, b) -> a.toUpperCase() + b.toUpperCase());
assertThat(result).isEqualTo("ABCDE");
}
@Test
public void givenUserList_whenReduceWithAgeAccumulatorAndSumCombiner_thenCorrect() {
List<User> users = Arrays.asList(new User("John", 30), new User("Julie", 35));
int result = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
assertThat(result).isEqualTo(65);
}
@Test
public void givenStringList_whenReduceWithParallelStream_thenCorrect() {
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
String result = letters.parallelStream().reduce("", String::concat);
assertThat(result).isEqualTo("abcde");
}
@Test
public void givenNumberUtilsClass_whenCalledDivideListElements_thenCorrect() {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
assertThat(NumberUtils.divideListElements(numbers, 1)).isEqualTo(21);
}
@Test
public void givenNumberUtilsClass_whenCalledDivideListElementsWithExtractedTryCatchBlock_thenCorrect() {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
assertThat(NumberUtils.divideListElementsWithExtractedTryCatchBlock(numbers, 1)).isEqualTo(21);
}
@Test
public void givenNumberUtilsClass_whenCalledDivideListElementsWithExtractedTryCatchBlockAndListContainsZero_thenCorrect() {
List<Integer> numbers = Arrays.asList(0, 1, 2, 3, 4, 5, 6);
assertThat(NumberUtils.divideListElementsWithExtractedTryCatchBlock(numbers, 1)).isEqualTo(21);
}
@Test
public void givenNumberUtilsClass_whenCalledDivideListElementsWithExtractedTryCatchBlockAndDividerIsZero_thenCorrect() {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
assertThat(NumberUtils.divideListElementsWithExtractedTryCatchBlock(numbers, 0)).isEqualTo(0);
}
@Test
public void givenStream_whneCalleddivideListElementsWithApplyFunctionMethod_thenCorrect() {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
assertThat(NumberUtils.divideListElementsWithApplyFunctionMethod(numbers, 1)).isEqualTo(21);
}
@Test
public void givenTwoStreams_whenCalledReduceOnParallelizedStream_thenFasterExecutionTime() {
List<User> userList = new ArrayList<>();
for (int i = 0; i <= 1000000; i++) {
userList.add(new User("John" + i, i));
}
long currentTime1 = System.currentTimeMillis();
userList.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
long sequentialExecutionTime = System.currentTimeMillis() -currentTime1;
long currentTime2 = System.currentTimeMillis();
userList.parallelStream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
long parallelizedExecutionTime = System.currentTimeMillis() - currentTime2;
assertThat(parallelizedExecutionTime).isLessThan(sequentialExecutionTime);
}
}

View File

@@ -0,0 +1,42 @@
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

@@ -0,0 +1,47 @@
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

@@ -0,0 +1,43 @@
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

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

View File

@@ -0,0 +1,87 @@
package com.baeldung.typeinference;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Test;
public class TypeInferenceUnitTest {
@Test
public void givenNoTypeInference_whenInvokingGenericMethodsWithTypeParameters_ObjectsAreCreated() {
// Without type inference. code is verbose.
Map<String, Map<String, String>> mapOfMaps = new HashMap<String, Map<String, String>>();
List<String> strList = Collections.<String> emptyList();
List<Integer> intList = Collections.<Integer> emptyList();
assertTrue(mapOfMaps.isEmpty());
assertTrue(strList.isEmpty());
assertTrue(intList.isEmpty());
}
@Test
public void givenTypeInference_whenInvokingGenericMethodsWithoutTypeParameters_ObjectsAreCreated() {
// With type inference. code is concise.
List<String> strListInferred = Collections.emptyList();
List<Integer> intListInferred = Collections.emptyList();
assertTrue(strListInferred.isEmpty());
assertTrue(intListInferred.isEmpty());
}
@Test
public void givenJava7_whenInvokingCostructorWithoutTypeParameters_ObjectsAreCreated() {
// Type Inference for constructor using diamond operator.
Map<String, Map<String, String>> mapOfMapsInferred = new HashMap<>();
assertTrue(mapOfMapsInferred.isEmpty());
assertEquals("public class java.util.HashMap<K,V>", mapOfMapsInferred.getClass()
.toGenericString());
}
static <T> List<T> add(List<T> list, T a, T b) {
list.add(a);
list.add(b);
return list;
}
@Test
public void givenGenericMethod_WhenInvokedWithoutExplicitTypes_TypesAreInferred() {
// Generalized target-type inference
List<String> strListGeneralized = add(new ArrayList<>(), "abc", "def");
List<Integer> intListGeneralized = add(new ArrayList<>(), 1, 2);
List<Number> numListGeneralized = add(new ArrayList<>(), 1, 2.0);
assertEquals("public class java.util.ArrayList<E>", strListGeneralized.getClass()
.toGenericString());
assertFalse(intListGeneralized.isEmpty());
assertEquals(2, numListGeneralized.size());
}
@Test
public void givenLambdaExpressions_whenParameterTypesNotSpecified_ParameterTypesAreInferred() {
// Type Inference and Lambda Expressions.
List<Integer> intList = Arrays.asList(5, 3, 4, 2, 1);
Collections.sort(intList, (a, b) -> {
assertEquals("java.lang.Integer", a.getClass().getName());
return a.compareTo(b);
});
assertEquals("[1, 2, 3, 4, 5]", Arrays.toString(intList.toArray()));
List<String> strList = Arrays.asList("Red", "Blue", "Green");
Collections.sort(strList, (a, b) -> {
assertEquals("java.lang.String", a.getClass().getName());
return a.compareTo(b);
});
assertEquals("[Blue, Green, Red]", Arrays.toString(strList.toArray()));
}
}

View File

@@ -0,0 +1,42 @@
package com.baeldung.util;
import static org.junit.Assert.assertEquals;
import java.time.Clock;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.temporal.ChronoField;
import org.junit.Test;
public class CurrentDateTimeUnitTest {
private static final Clock clock = Clock.fixed(Instant.parse("2016-10-09T15:10:30.00Z"), ZoneId.of("UTC"));
@Test
public void shouldReturnCurrentDate() {
final LocalDate now = LocalDate.now(clock);
assertEquals(9, now.get(ChronoField.DAY_OF_MONTH));
assertEquals(10, now.get(ChronoField.MONTH_OF_YEAR));
assertEquals(2016, now.get(ChronoField.YEAR));
}
@Test
public void shouldReturnCurrentTime() {
final LocalTime now = LocalTime.now(clock);
assertEquals(15, now.get(ChronoField.HOUR_OF_DAY));
assertEquals(10, now.get(ChronoField.MINUTE_OF_HOUR));
assertEquals(30, now.get(ChronoField.SECOND_OF_MINUTE));
}
@Test
public void shouldReturnCurrentTimestamp() {
final Instant now = Instant.now(clock);
assertEquals(clock.instant().getEpochSecond(), now.getEpochSecond());
}
}

View File

@@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear