简体   繁体   中英

Get Property that has max Character size from list of objects java

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()

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM