Salve stavo svolgendo qualche esercizio per esercitarmi sugli Stream e mi sono imbattuto in questo problema: ho le seguenti Classi
public class Person {
private final String name;
private final Optional<String> city;
private final double income;
private final Set<String> jobs;
public Person(final String name, final String city, final double income, String... jobs) {
this.name = name;
this.city = Optional.of(city);
this.income = income;
this.jobs = new HashSet<>(Arrays.asList(jobs));
}
public String getName() {
return this.name;
}
public Optional<String> getCity() {
return this.city;
}
public double getIncome() {
return this.income;
}
public Set<String> getJobs() {
return Collections.unmodifiableSet(jobs);
}
public class UsePerson {
public static void main(String[] args) {
// TODO Auto-generated method stub
final List<Person> plist = new ArrayList<>();
plist.add(new Person("Mario" ,"Cesena" ,20000 , "Teacher"));
plist.add(new Person("Rino" ,"Forlì" ,50000 , " Professor"));
plist.add(new Person("Lino" ,"Cesena" ,110000 , "Professor", "Dean"));
plist.add(new Person("Ugo", "Cesena", 20000, "Secretary"));
//plist.add(new Person("Marco", null, 4000, "Contractor"));
final double res = plist.stream().filter(p -> p.getCity().isPresent())
.filter(p -> p.getCity().get().equals("Cesena")).peek(System.out::println)
.mapToDouble(Person::getIncome).sum();
System.out.println(res);
}
}
Il problema nasce quando "decommento" l'ultima persona da aggiungere (Marco), quel null lancia un NullPointerException.