我正在尝试找到具有最大长度的 java 给定属性的字符串。我会将属性名称作为字符串传递给方法,该方法将返回最大长度的字符串值。
class Employee {
private String name;
private String designation;
private List<Address> address;
private ContactInfo contactInfo;
....
getter setter
}
class Address {
private String city;
private String state;
private String country;
......
getter setter
}
class ContactInfo {
private String mobileNumber;
private String landlineNumber;
....
getter setter
}
Run Code Online (Sandbox Code Playgroud)
我有一些数据如下:
ContactInfo contactInfo = new ContactInfo("84883838", "12882882");
Address address1 = new Address("city111", "state111", "country111");
Address address2 = new Address("city111111", "state11112", "country1112");
Employee employee1 = new Employee("xyz", "uyyy", List.of(address1, address2), contactInfo);
private String findStringWithMaxLength(String attribute) {
return employeeList.stream()
....
}
Run Code Online (Sandbox Code Playgroud)
在上述情况下,如果我将属性值提供为“city”,那么由于最大字符串长度,它应该返回值“city111111”。
如果我们有子对象和对象列表,我该如何遍历给定的属性。
您可以创建一个方法来获取员工列表和一个函数来获取特定属性,如下所示:
private String findStringWithMaxLength(List<Employee> employees, Function<Employee, String> function) {
return employees.stream()
.map(function)
.max(Comparator.comparing(String::length))
.orElseThrow(() -> new IllegalArgumentException("Empty list"));
}
Run Code Online (Sandbox Code Playgroud)
并调用您可以使用的方法:
findStringWithMaxLength(employees, Employee::getName)
findStringWithMaxLength(employees, Employee::getDesignation)
findStringWithMaxLength(employees, Employee::getAddress)
Run Code Online (Sandbox Code Playgroud)
请注意,如果列表为空,该方法将抛出异常,如果不抛出异常,则可以将其替换为 orElse(withDefaultValue)
| 归档时间: |
|
| 查看次数: |
80 次 |
| 最近记录: |