我有以下课程:
class Employee
{
private String name;
private List<Address> addresses;
//...
//Getters and setters for all fields
}
public class Address
{
private String city;
private Timestamp startDate;
private Timestamp endDate;
private String typeOfResidence;
private String businessCode;
private String businessType;
//...
//Getters and setters for all the fields
}
现在我有一个员工对象,其中包含地址列表。基于businessCode,我需要填充businessType。
已填充businessCode。
我有一个功能
public String public getBusinessType(String businessCode){
...
business logic...
return businessType;
}
现在请帮助更新每个地址元素中的businessType字段。
我正在尝试使用
List<Address> l = employee.getAddress();
IntStream.range(0, l.size).forEach();
但不确定如何为每个地址元素调用getBusinessType并更新每个地址元素中的字段。
答案 0 :(得分:3)
您可以在不需要流式传输的情况下执行此操作:
yourList.forEach(x -> {
x.setBusinessType(YourClass.getBusinessType(x.getBusinessCode()))
})
答案 1 :(得分:2)
使用 for-each 循环的经典方法是:
for(Address a : employee.getAddress()){
a.setBusinessType(getBusinessType(a.getBusinessCode()));
}
使用Streams
将是:
employee.getAddress().stream().forEach(a-> a.setBusinessType(getBusinessType(a.getBusinessCode())));
但是(一个好的IDE会告诉你)stream()
在这里是多余的; List.forEach()
就足够了:
employee.getAddress().forEach(a-> a.setBusinessType(getBusinessType(a.getBusinessCode())));
答案 2 :(得分:-2)
应该是这样的
employee.getAddress().stream().map(address->address.setBusinessType(getBusinessType(address.getBusinessCode())))
.collect(Colletors.toList());
您也可以使用replaceAll方法。
为了便于阅读,请创建UnaryOperator<T>
,然后在replaceAll
方法中使用此功能。
UnaryOperator<Address> updateBusinessType = address -> {
address.setBusinessType(...);
return address;
};
employee.getAddress().replaceAll(updateBusinessType);
通过在Address
类中定义更新businessType
属性的方法,也可以改进它。
答案 3 :(得分:-2)
请参阅下面的一行。
employee.getAddresses().forEach(employee-> employee.setCity("My City"))