Missing Code - Guide To Java 8 Optional
This commit is contained in:
Maiklins 2020-01-21 10:03:23 +01:00 committed by Grzegorz Piwowarek
parent 37170bb97c
commit 0caf728a2f
1 changed files with 36 additions and 1 deletions

View File

@ -1,6 +1,8 @@
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());
}
}