The Problem
I would like to summarize Person
objects. Use the lastName if it is not null; if null, then use the firstName; else use the birthDay. If all these are null
, then use the default text UNKNOWN
.
Usually, you write something like this:
String summary = "";
if(p.getLastName() != null){
summary = p.getLastName();
}
else if(p.getFirstName() != null){
summary = p.getFirstName();
}
else if (p.getBirthDate() != null){
summary = p.getBirthDate.toString();
}
else{
summary = "UNKNOWN";
}
So far so good, but the many if-then-else sequence is hard to read.
The Solution
Streams offer a bit more elegant way to do this.
String summary = Stream.of(
getLastName(),
getFirstName(),
getBirthDate() != null ?getBirthDate().toString():null)
.filter(Objects::nonNull)
.findFirst()
.orElse("UNKNOWN");
Sample run
Let’s run some cases:
System.out.println(new Person("John", "Doe",randomDate()).getSummary());
System.out.println(new Person("John", null,randomDate()).getSummary());
System.out.println(new Person(null, null,randomDate()).getSummary());
System.out.println(new Person(null, null,null).getSummary());
System.out.println(new Person(null, "Doe",randomDate()).getSummary());
System.out.println(new Person(null, "Doe",null).getSummary());
Output is:
Doe
John
2023-06-12
UNKNOWN
Doe
Doe
Complete code snippet
import java.time.LocalDate;
import java.util.Objects;
import java.util.Random;
import java.util.stream.Stream;
public class Person {
private String firstName;
private String lastName;
private LocalDate birthDate;
public Person(String firstName, String lastName, LocalDate birthDate) {
this.firstName = firstName;
this.lastName = lastName;
this.birthDate = birthDate;
}
public String getFirstName(){
return firstName;
}
public String getLastName() {
return lastName;
}
public LocalDate getBirthDate() {
return birthDate;
}
public String getBirthMonth(){
return getBirthDate().getMonth().name();
}
@Override
public String toString() {
return "Person{" +
"firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", birthDate=" + birthDate +
'}';
}
public String getSummary(){
return Stream.of(getLastName(),
getFirstName(),
getBirthDate() != null ?getBirthDate().toString():null)
.filter(Objects::nonNull)
.findFirst()
.orElse("UNKNOWN");
}
// helper method to generate a random date up till a year ago
public static LocalDate randomDate(){
return LocalDate.now().minusDays(new Random().nextInt(366));
}
public static void main(String[] args){
System.out.println(new Person("John", "Doe",randomDate()).getSummary());
System.out.println(new Person("John", null,randomDate()).getSummary());
System.out.println(new Person(null, null,randomDate()).getSummary());
System.out.println(new Person(null, null,null).getSummary());
System.out.println(new Person(null, "Doe",randomDate()).getSummary());
System.out.println(new Person(null, "Doe",null).getSummary());
}
}