Missing Code - Guide To Java 8 Optional
package com.baeldung.optional;
+import java.util.List;
import java.util.Optional;
+import java.util.stream.Collectors;
public class Person {
private String name;
@@ -21,7 +23,7 @@ public class Person {
}
public Optional<Integer> getAge() {
- return Optional.ofNullable(age);
+ return Optional.of(age);
}
public void setAge(int age) {
@@ -36,4 +38,37 @@ public class Person {
return Optional.ofNullable(password);
}
+ public static List<Person> search(List<Person> people, String name, Optional<Integer> age) {
+ // Null checks for people and name
+ return people.stream()
+ .filter(p -> p.getName().equals(name))
+ .filter(p -> p.getAge().get() >= age.orElse(0))
+ .collect(Collectors.toList());
+ }
+
+ public static List<Person> search(List<Person> people, String name, Integer age) {
+ // Null checks for people and name
+ final Integer ageFilter = age != null ? age : 0;
+
+ return people.stream()
+ .filter(p -> p.getName().equals(name))
+ .filter(p -> p.getAge().get() >= ageFilter)
+ .collect(Collectors.toList());
+ }
+
+ public static List<Person> search(List<Person> people, String name) {
+ return doSearch(people, name, 0);
+ }
+
+ public static List<Person> search(List<Person> people, String name, int age) {
+ return doSearch(people, name, age);
+ }
+
+ private static List<Person> doSearch(List<Person> people, String name, int age) {
+ // Null checks for people and name
+ return people.stream()
+ .filter(p -> p.getName().equals(name))
+ .filter(p -> p.getAge().get().intValue() >= age)
+ .collect(Collectors.toList());
+ }
}
