Optional demo.

This commit is contained in:
Paweł Dyda 2022-11-15 20:26:48 +01:00
parent a37f8801d4
commit 4695639b8f
4 changed files with 106 additions and 0 deletions

View File

@ -0,0 +1,15 @@
package pl.amu.edu.demo.data;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.experimental.FieldDefaults;
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@FieldDefaults(level = AccessLevel.PUBLIC, makeFinal = true)
@Builder(toBuilder = true)
public class Address {
String addressLine1 = "Northern Bridge";
String addressLine2 = null;
String zipCode = "01-868";
}

View File

@ -0,0 +1,24 @@
package pl.amu.edu.demo.data;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.experimental.FieldDefaults;
import java.util.Optional;
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@FieldDefaults(level = AccessLevel.PUBLIC, makeFinal = true)
@Getter
@Builder
public class Housing {
Address address;
boolean isApartment;
Double area;
public Optional<String> zipCode() {
return Optional.ofNullable(address).map(address -> address.zipCode);
}
}

View File

@ -0,0 +1,29 @@
package pl.amu.edu.demo.data;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.experimental.FieldDefaults;
import java.time.LocalDate;
import java.util.Objects;
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@FieldDefaults(level = AccessLevel.PUBLIC, makeFinal = true)
@Getter
@Builder
public class Person {
String displayName;
String firstName;
String lastName;
LocalDate birthDate;
Housing housing;
boolean isMarried;
public boolean isAdult() {
return Objects.nonNull(birthDate) &&
LocalDate.now().minusYears(18).isAfter(birthDate);
}
}

View File

@ -0,0 +1,38 @@
package pl.amu.edu.demo.maybe;
import pl.amu.edu.demo.data.Address;
import pl.amu.edu.demo.data.Housing;
import pl.amu.edu.demo.data.Person;
import java.time.LocalDate;
import java.util.Optional;
public class OptionalExample {
public static void main(String[] args) {
new OptionalExample().run();
}
private void run() {
var person = Person.builder()
.displayName("Gąska Balbinka").birthDate(LocalDate.ofYearDay(1959, 1)).build();
var address = Address.builder().build();
var underTheBridge = Housing.builder().area(0.2).address(address).build();
var maybeAdult = Optional.ofNullable(person)
.filter(Person::isAdult);
var housing = maybeAdult
.map(Person::getHousing)
.orElse(underTheBridge);
var zipCode = Optional.of(housing)
.flatMap(Housing::zipCode)
.orElseThrow();
maybeAdult
.map(Person::getBirthDate)
.map(birthDate -> {
var name = person.displayName;
return String.format("%s: born %s lives at %s area.", name, birthDate, zipCode);
})
.ifPresent(System.out::println);
}
}