Skip to content

Instantly share code, notes, and snippets.

public class FXService {
private final CurrencyConverter currencyConverter;
private final BankService bankService;
private final double commissionPer;
public String transfer(Money money, BankAccount destinationAccount, Currency target) {
String sourceCurrency = money.currency().name();
String targetCurrency = target.name();
List<Person> p = searchPersonById("100");
if (p.isEmpty()) {
System.out.println("No result");
} else {
System.out.println("Person" + p.get(0));
}
//Address has priority , first home and then Office
Optional<String> address = Stream
.of(person.getHome().map(Home::getAddress), person.getOffice().map(Office::getAddress))
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst();
address
.ifPresent(add -> System.out.println("Contacting at address " + add));
p.getHome().ifPresent(a -> System.out.println("Sending Postal mail " + a.address));
p.getHome()
.flatMap(Person.Home::getInsurance)
.ifPresent(a -> System.out.println("Sending Notification to insurance " + a.agency));
//Don't do this
System.out.println("Calling Phone " + phone.get());
System.out.println("Sending Email " + email.get());
//Use ifPresent to avoid runtime error
phone.ifPresent(contact -> System.out.println("Sending email to " + contact));
email.ifPresent(contact -> System.out.println("Calling " + contact));
//Use IfPresent & other cool things
phone
.filter(number -> hasOptIn(number))
.ifPresent(number -> System.out.println("Calling Phone " + number));
email
.filter(m -> hasOptIn(m))
.ifPresent(m -> System.out.println("Sending Email " + m));
//Use Optional
p.getEmail().ifPresent(email -> System.out.println("Sending email to " + email));
p.getPhone().ifPresent(phone -> System.out.println("Calling " + phone));
//Optional for Collection or Search type of request
Optional<Person> person = persons.stream().findFirst();
person.ifPresent(System.out::println);
public Optional<String> getEmail() {
return Optional.ofNullable(email);
}
public Optional<String> getPhone() {
return Optional.ofNullable(phone);
}
//Address has priority , first home and then Office
if (p.home != null) {
System.out.println("Contacted at home address " + p.home.address);
return; // Magical return for early exit
}
if (p.office != null) {
System.out.println("Contacted at office address " + p.office.address);
return; // Magical return for early exit
//Nested Property
if (p.getHome() != null) {
System.out.println("Sending Postal mail " + p.getHome().address);
}
if (p.getHome() != null && p.getHome().getInsurance() != null) {
System.out.println("Sending Notification to insurance " + p.getHome().getInsurance().getAgency());
}