首页 > 解决方案 > 在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”。

如果我们有子对象和对象列表,我该如何遍历给定的属性。

标签: javajava-8

解决方案


您可以创建一个获取员工列表的方法和一个获取特定属性的函数,如下所示:

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)


推荐阅读