4 回答

TA貢獻(xiàn)1719條經(jīng)驗(yàn) 獲得超6個(gè)贊
Emplist.stream().map((emp)->{
If(emp.getName().equals("robert")){
emp.setName("ronald") ;
return emp;
}else{
return emp;}}).collect(Collectors.toList());

TA貢獻(xiàn)1878條經(jīng)驗(yàn) 獲得超4個(gè)贊
empList = (ArrayList<Employee>) empList.stream() .filter(emp -> emp.getFirstName().equalsIgnoreCase("Robert")) .peek(emp -> emp.setFirstName("Ronald")) .collect(Collectors.toList());
由于您想更改原始列表,請(qǐng)將收集的列表分配給原始列表

TA貢獻(xiàn)1752條經(jīng)驗(yàn) 獲得超4個(gè)贊
一個(gè)簡(jiǎn)單的 forEach 版本(get/set 方法被忽略)
list.forEach(e -> {
if (e.firstName.equals("Robert")) {
e.firstName = "Ronald";
}
});

TA貢獻(xiàn)1856條經(jīng)驗(yàn) 獲得超5個(gè)贊
您可以填充Map要轉(zhuǎn)換為的名稱。
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);
}
}
添加回答
舉報(bào)