如何使用stream在Java8中修改列表的每个元素中的字段
我有以下课程:如何使用stream在Java8中修改列表的每个元素中的字段,java,java-8,java-stream,Java,Java 8,Java Stream,我有以下课程: 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 Timestam
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
}
现在请帮助更新每个地址元素中的businessType字段
我正在尝试使用
List<Address> l = employee.getAddress();
IntStream.range(0, l.size).forEach();
List l=employee.getAddress();
IntStream.range(0,l.size).forEach();
但不确定如何为每个地址元素调用getBusinessType并更新每个地址元素中的字段。应该是这样的
employee.getAddress().stream().map(address->address.setBusinessType(getBusinessType(address.getBusinessCode())))
.collect(Colletors.toList());
你也可以使用这个方法
要提高可读性,请创建UnaryOperator
,然后在replaceAll
方法中使用此函数
UnaryOperator<Address> updateBusinessType = address -> {
address.setBusinessType(...);
return address;
};
employee.getAddress().replaceAll(updateBusinessType);
UnaryOperator updateBusinessType=地址->{
地址。setBusinessType(…);
回信地址;
};
employee.getAddress().replaceAll(updateBusinessType);
还可以通过在Address
类中定义更新businessType
属性的方法来改进它。使用for each循环的经典方法是:
for(Address a : employee.getAddress()){
a.setBusinessType(getBusinessType(a.getBusinessCode()));
}
employee.getAddress().stream().forEach(a-> a.setBusinessType(getBusinessType(a.getBusinessCode())));
使用流
可以:
for(Address a : employee.getAddress()){
a.setBusinessType(getBusinessType(a.getBusinessCode()));
}
employee.getAddress().stream().forEach(a-> a.setBusinessType(getBusinessType(a.getBusinessCode())));
但是(一个好的IDE会告诉您,流()
在这里是多余的<代码>列表。forEach()足够:
employee.getAddress().forEach(a-> a.setBusinessType(getBusinessType(a.getBusinessCode())));
您可以在不需要流的情况下就地完成:
yourList.forEach(x -> {
x.setBusinessType(YourClass.getBusinessType(x.getBusinessCode()))
})
请参阅下一行
employee.getAddresses().forEach(employee-> employee.setCity("My City"))
employee.getAddress().forEach(a->a.setBusinessType(…)
;你不需要把它变成一个街区。void
方法是forEach()
@Andreas的有效lambda表达式,我知道。有时为了清晰起见,我会这样做replaceAll()
需要一个UnaryOperator
,但是setBusinessType
不会返回修改后的地址
对象。很抱歉,我看不到用已经存在的值替换列表中的所有值的意义。使用forEach()
要好得多。使用replaceAll()
会让人感到困惑,因为我们会坐在那里,试图找出您要替换的内容,这是浪费时间,因为您实际上并没有替换列表中的地址
对象。或者这是一个代码混淆的练习。如果是这样的话,那就糟糕了。