4 回答
TA贡献1719条经验 获得超6个赞
Emplist.stream().map((emp)->{
If(emp.getName().equals("robert")){
emp.setName("ronald") ;
return emp;
}else{
return emp;}}).collect(Collectors.toList());
TA贡献1878条经验 获得超4个赞
empList = (ArrayList<Employee>) empList.stream() .filter(emp -> emp.getFirstName().equalsIgnoreCase("Robert")) .peek(emp -> emp.setFirstName("Ronald")) .collect(Collectors.toList());
由于您想更改原始列表,请将收集的列表分配给原始列表
TA贡献1752条经验 获得超4个赞
一个简单的 forEach 版本(get/set 方法被忽略)
list.forEach(e -> {
if (e.firstName.equals("Robert")) {
e.firstName = "Ronald";
}
});
TA贡献1856条经验 获得超5个赞
您可以填充Map要转换为的名称。
import java.util.*;
import java.util.stream.Collectors;
public class Employee {
private String firstName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public Employee(String firstName) {
this.firstName = firstName;
}
@Override
public String toString() {
return String.format("Employee [firstName=%s]", firstName);
}
public static void main(String[] args) {
Map<String, String> dict = new HashMap<String, String>() {
private static final long serialVersionUID = -4824000127068129154L;
{
put("Robert", "Donald");
}
};
List<Employee> employees = Arrays.asList("Adam", "James", "Robert").stream().map(Employee::new).collect(Collectors.toList());
employees = employees.stream().map(emp -> {
if (dict.containsKey(emp.getFirstName())) {
emp.setFirstName(dict.get(emp.getFirstName()));
}
return emp;
}).collect(Collectors.toList());
employees.stream().forEach(System.out::println);
}
}
添加回答
举报