diff --git a/call-all-getters/src/main/java/com/baeldung/reflection/util/Utils.java b/call-all-getters/src/main/java/com/baeldung/reflection/util/Utils.java index 665717db09..c9542bbdf2 100644 --- a/call-all-getters/src/main/java/com/baeldung/reflection/util/Utils.java +++ b/call-all-getters/src/main/java/com/baeldung/reflection/util/Utils.java @@ -3,9 +3,10 @@ package com.baeldung.reflection.util; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; -import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.function.Predicate; +import java.util.stream.Collectors; import com.baeldung.reflection.model.Customer; @@ -15,20 +16,28 @@ public class Utils { PropertyDescriptor[] propDescArr = Introspector.getBeanInfo(Customer.class, Object.class).getPropertyDescriptors(); List propDescList = Arrays.asList(propDescArr); - List nullProps = new ArrayList(); - - propDescList.stream().forEach(p -> { - Method getterMethod = p.getReadMethod(); - try { - if (getterMethod != null && getterMethod.invoke(customer) == null) { - // If the value if null for that field - nullProps.add(p.getName()); - } - } catch (Exception e) { - // Handle the exception - e.printStackTrace(); - } - }); + List nullProps = propDescList.stream() + .filter(nulls(customer)) + .map(PropertyDescriptor::getName) + .collect(Collectors.toList()); return nullProps; } + + private static Predicate nulls(Customer customer) { + Predicate isNull = new Predicate() { + @Override + public boolean test(PropertyDescriptor pd) { + Method getterMethod = pd.getReadMethod(); + boolean result = false; + try { + result = (getterMethod != null && getterMethod.invoke(customer) == null); + } catch (Exception e) { + // Handle the exception + e.printStackTrace(); + } + return result; + } + }; + return isNull; + } }