java - 在java 8中查找具有给定属性的最大长度的字符串作为字符串
问题描述
我正在尝试查找具有给定 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
}
我有一些数据,如下所示:
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()
....
}
在上述情况下,如果我将属性值提供为“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"));
}
并调用您可以使用的方法:
findStringWithMaxLength(employees, Employee::getName)
findStringWithMaxLength(employees, Employee::getDesignation)
findStringWithMaxLength(employees, Employee::getAddress)
请注意,如果列表为空,该方法将抛出异常,如果您不会抛出异常,则可以将其替换为orElse(withDefaultValue)
推荐阅读
- reactjs - 使用 Material-UI 进行酶浅测试
- c# - 为什么 ExecuteNonQuery 会返回“输入在此上下文中无效”(ASP.NET | Ole Db)?
- android - 包含嵌套 RecyclerViews 的 BottomSheetBehavior ViewGroup 的垂直滚动不一致
- javascript - 如何保持文字的比例?
- angular - agm-marker-cluster 中的图像路径格式是什么,如何为不同类型分配不同的标记簇图标?
- exchangewebservices - Route exchange online public folder hierarchy requests failed with "Expected an item Id but received a folder Id"
- r - R如果一列中的值再次出现在另一列中而没有循环,则删除行
- bash - 如何使用 bash 将 if then 语句添加到具有多个参数的值
- spring - How to build a nonblocking Consumer when using AsyncRabbitTemplate with Request/Reply Pattern
- csv - 将 csv 保存为 txt 仅一列数据