Got Code Clean up #24

Merged
honeymoose merged 1 commits from java-8 into main 2024-05-01 11:53:17 -04:00
37 changed files with 20 additions and 1262 deletions

View File

@ -1,9 +0,0 @@
package com.baeldung.aspect;
public aspect ChangeCallsToCurrentTimeInMillisMethod {
long around():
call(public static native long java.lang.System.currentTimeMillis())
&& within(user.code.base.pckg.*) {
return 0;
}
}

View File

@ -1,14 +0,0 @@
package com.baeldung.java_8_features;
public class Address {
private String street;
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
}

View File

@ -1,4 +0,0 @@
package com.baeldung.java_8_features;
public class CustomException extends RuntimeException {
}

View File

@ -1,16 +0,0 @@
package com.baeldung.java_8_features;
import java.util.Optional;
public class OptionalAddress {
private String street;
public Optional<String> getStreet() {
return Optional.ofNullable(street);
}
public void setStreet(String street) {
this.street = street;
}
}

View File

@ -1,16 +0,0 @@
package com.baeldung.java_8_features;
import java.util.Optional;
public class OptionalUser {
private OptionalAddress address;
public Optional<OptionalAddress> getAddress() {
return Optional.of(address);
}
public void setAddress(OptionalAddress address) {
this.address = address;
}
}

View File

@ -1,40 +0,0 @@
package com.baeldung.java_8_features;
import java.util.Optional;
public class User {
private String name;
private Address address;
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public User() {
}
public User(String name) {
this.name = name;
}
public static boolean isRealUser(User user) {
return true;
}
public String getOrThrow() {
String value = null;
Optional<String> valueOpt = Optional.ofNullable(value);
String result = valueOpt.orElseThrow(CustomException::new).toUpperCase();
return result;
}
public boolean isLegalName(String name) {
return name.length() > 3 && name.length() < 16;
}
}

View File

@ -1,18 +0,0 @@
package com.baeldung.java_8_features;
public interface Vehicle {
void moveTo(long altitude, long longitude);
static String producer() {
return "N&F Vehicles";
}
default long[] startPosition() {
return new long[] { 23, 15 };
}
default String getOverview() {
return "ATV made by " + producer();
}
}

View File

@ -1,9 +0,0 @@
package com.baeldung.java_8_features;
public class VehicleImpl implements Vehicle {
@Override
public void moveTo(long altitude, long longitude) {
// do nothing
}
}

View File

@ -1,19 +0,0 @@
package com.baeldung.nullsafecollectionstreams;
import java.util.Collection;
import java.util.stream.Stream;
import static org.apache.commons.collections4.CollectionUtils.emptyIfNull;
public class NullSafeCollectionStreamsUsingCommonsEmptyIfNull {
/**
* This method shows how to make a null safe stream from a collection through the use of
* emptyIfNull() method from Apache Commons CollectionUtils library
*
* @param collection The collection that is to be converted into a stream
* @return The stream that has been created from the collection or an empty stream if the collection is null
*/
public Stream<String> collectionAsStream(Collection<String> collection) {
return emptyIfNull(collection).stream();
}
}

View File

@ -1,21 +0,0 @@
package com.baeldung.nullsafecollectionstreams;
import java.util.Collection;
import java.util.Optional;
import java.util.stream.Stream;
public class NullSafeCollectionStreamsUsingJava8OptionalContainer {
/**
* This method shows how to make a null safe stream from a collection through the use of
* Java SE 8s Optional Container
*
* @param collection The collection that is to be converted into a stream
* @return The stream that has been created from the collection or an empty stream if the collection is null
*/
public Stream<String> collectionAsStream(Collection<String> collection) {
return Optional.ofNullable(collection)
.map(Collection::stream)
.orElseGet(Stream::empty);
}
}

View File

@ -1,20 +0,0 @@
package com.baeldung.nullsafecollectionstreams;
import java.util.Collection;
import java.util.stream.Stream;
public class NullSafeCollectionStreamsUsingNullDereferenceCheck {
/**
* This method shows how to make a null safe stream from a collection through the use of a check
* to prevent null dereferences
*
* @param collection The collection that is to be converted into a stream
* @return The stream that has been created from the collection or an empty stream if the collection is null
*/
public Stream<String> collectionAsStream(Collection<String> collection) {
return collection == null ? Stream.empty() : collection.stream();
}
}

View File

@ -1,11 +0,0 @@
package com.baeldung.strategy;
import java.math.BigDecimal;
public class ChristmasDiscounter implements Discounter {
@Override
public BigDecimal apply(BigDecimal amount) {
return amount.multiply(BigDecimal.valueOf(0.9));
}
}

View File

@ -1,23 +0,0 @@
package com.baeldung.strategy;
import java.math.BigDecimal;
import java.util.function.UnaryOperator;
public interface Discounter extends UnaryOperator<BigDecimal> {
default Discounter combine(Discounter after) {
return value -> after.apply(this.apply(value));
}
static Discounter christmas() {
return (amount) -> amount.multiply(BigDecimal.valueOf(0.9));
}
static Discounter newYear() {
return (amount) -> amount.multiply(BigDecimal.valueOf(0.8));
}
static Discounter easter() {
return (amount) -> amount.multiply(BigDecimal.valueOf(0.5));
}
}

View File

@ -1,11 +0,0 @@
package com.baeldung.strategy;
import java.math.BigDecimal;
public class EasterDiscounter implements Discounter {
@Override
public BigDecimal apply(BigDecimal amount) {
return amount.multiply(BigDecimal.valueOf(0.5));
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung.monad;
package com.ossez.monad;
import java.util.Optional;
import java.util.function.Function;

View File

@ -1,4 +1,4 @@
package com.baeldung.spliterator;
package com.ossez.spliterator;
import java.util.List;

View File

@ -1,4 +1,4 @@
package com.baeldung.spliterator;
package com.ossez.spliterator;
public class Author {
private String name;

View File

@ -1,4 +1,4 @@
package com.baeldung.spliterator;
package com.ossez.spliterator;
import java.util.List;
import java.util.Spliterator;

View File

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

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

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

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

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

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

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

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

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

@ -1,50 +0,0 @@
/*
* 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

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

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

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

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

@ -1,5 +1,6 @@
package com.baeldung.monad;
package com.ossez.monad;
import com.ossez.monad.*;
import org.junit.Assert;
import org.junit.Test;

View File

@ -4,13 +4,14 @@ 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 =
private final NullSafeCollectionStreamsUsingCommonsEmptyIfNull instance =
new NullSafeCollectionStreamsUsingCommonsEmptyIfNull();
@Test

View File

@ -5,6 +5,7 @@ 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.*;
@ -14,7 +15,7 @@ import static org.junit.Assert.*;
*/
public class NullSafeCollectionStreamsUsingNullDereferenceCheckUnitTest {
private final NullSafeCollectionStreamsUsingNullDereferenceCheck instance =
private final NullSafeCollectionStreamsUsingNullDereferenceCheck instance =
new NullSafeCollectionStreamsUsingNullDereferenceCheck();
@Test

View File

@ -1,4 +1,4 @@
package com.baeldung.spliterator;
package com.ossez.spliterator;
import static org.assertj.core.api.Assertions.assertThat;
@ -10,6 +10,10 @@ import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.ossez.spliterator.Article;
import com.ossez.spliterator.Author;
import com.ossez.spliterator.CustomSpliterator;
import org.junit.Before;
import org.junit.Test;

View File

@ -7,6 +7,9 @@ import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import static com.ossez.strategy.Discounter.christmas;
import static com.ossez.strategy.Discounter.easter;
import static com.ossez.strategy.Discounter.newYear;
import static org.assertj.core.api.Assertions.assertThat;
public class StrategyDesignPatternUnitTest {
@ -50,7 +53,7 @@ public class StrategyDesignPatternUnitTest {
@Test
public void shouldApplyAllDiscounts() {
List<Discounter> discounters = Arrays.asList(Discounter.christmas(), Discounter.newYear(), Discounter.easter());
List<Discounter> discounters = Arrays.asList(christmas(), newYear(), easter());
BigDecimal amount = BigDecimal.valueOf(100);
@ -65,7 +68,7 @@ public class StrategyDesignPatternUnitTest {
public void shouldChainDiscounters() {
final Function<BigDecimal, BigDecimal> combinedDiscounters = Discounter
.christmas()
.andThen(Discounter.newYear());
.andThen(newYear());
combinedDiscounters.apply(BigDecimal.valueOf(100));
}