0

I have an List<Staff> where i will be getting those values from db. I need to find the max character size of a specific field which will be dynamic. For now im able to get the max size of firstName but its kind of hardcoded as shown below.

 public class Staff {

    private String firstName;
    private String lastName;
    private String surName;
    private String mailId;
}

List<String> fields = Arrays.asList("firstName", "lastName", "surName");
List<Staff> staffList = staffRepository.findAll();

fields.stream.map(field ->
Long maxLength = staffList.stream()
.map(Staff::getFirstName()) // i need to pass the field which will be dynamically changing
.mapToInt(String::length)
.max()).mapToLong(max -> max.orElse(0)).sum()
  • If the number of staff is quite large, reading them all into memory could be very inefficient. This could all be done on the database side with a native query. – David Conrad May 01 '20 at 19:31

1 Answers1

1

There are multiple ways to access property values as explained in this thread

So basically, you can write something like this to access value

private static Optional<Method> getMethodForField(Class clazz, String fieldName) throws IntrospectionException {
return Arrays.stream(Introspector.getBeanInfo(clazz).getPropertyDescriptors())
  .filter(propertyDescriptor -> propertyDescriptor.getName().equalsIgnoreCase(fieldName))
  .findFirst()
  .map(PropertyDescriptor::getReadMethod);

}

then Access Length of field, create another method

private static int getFieldLength(Staff staff, Method readMethod)  {
try {
  return ((String) readMethod.invoke(staff)).length();
} catch(Exception e){ }
return 0;

}

and now finally code to calculate max.

Optional<Method> readMethod = getMethodForField(Staff.class, "firstName");

if (readMethod.isPresent()) {
   staffList.stream()
    .mapToInt(data -> getFieldLength(data, readMethod.get()))
    .max();
}

you can wrap this in method and iterate over fields to calculate max for all of them.

lucid
  • 2,722
  • 1
  • 12
  • 24