Move null check logic to separate method
Move null check logic to separate method
@@ -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<PropertyDescriptor> propDescList = Arrays.asList(propDescArr);
- List<String> nullProps = new ArrayList<String>();
+ List<String> nullProps = propDescList.stream()
+ .filter(nulls(customer))
+ .map(PropertyDescriptor::getName)
+ .collect(Collectors.toList());
+ return nullProps;
+ }
- propDescList.stream().forEach(p -> {
- Method getterMethod = p.getReadMethod();
+ private static Predicate<PropertyDescriptor> nulls(Customer customer) {
+ Predicate<PropertyDescriptor> isNull = new Predicate<PropertyDescriptor>() {
+ @Override
+ public boolean test(PropertyDescriptor pd) {
+ Method getterMethod = pd.getReadMethod();
+ boolean result = false;
try {
- if (getterMethod != null && getterMethod.invoke(customer) == null) {
- // If the value if null for that field
- nullProps.add(p.getName());
- }
+ result = (getterMethod != null && getterMethod.invoke(customer) == null);
} catch (Exception e) {
// Handle the exception
e.printStackTrace();
}
- });
- return nullProps;
+ return result;
+ }
+ };
+ return isNull;
}
}
