Java 8将员工的名字从Robert更改为Ronald,并返回原始列表
数组列表中有15个这样的对象 我想更改原始区域列表,以便 名字叫Robert的地方,使用Java8API的一个简单的forEach版本(忽略get/set方法)就变成了RonaldJava 8将员工的名字从Robert更改为Ronald,并返回原始列表,java,java-8,Java,Java 8,数组列表中有15个这样的对象 我想更改原始区域列表,以便 名字叫Robert的地方,使用Java8API的一个简单的forEach版本(忽略get/set方法)就变成了Ronald Employee { String firstName; // Few other fields here } e1.firstName = Robert e2.firstName = Donald 您可以填充要转换为的名称的映射 list.forEach(e -> { if
Employee {
String firstName;
// Few other fields here
}
e1.firstName = Robert
e2.firstName = Donald
您可以填充要转换为的名称的
映射
list.forEach(e -> {
if (e.firstName.equals("Robert")) {
e.firstName = "Ronald";
}
});
import java.util.*;
导入java.util.stream.collector;
公营雇员{
私有字符串名;
公共字符串getFirstName(){
返回名字;
}
public void setFirstName(字符串firstName){
this.firstName=firstName;
}
公共雇员(字符串名){
this.firstName=firstName;
}
@凌驾
公共字符串toString(){
返回String.format(“Employee[firstName=%s]”,firstName);
}
公共静态void main(字符串[]args){
Map dict=newhashmap(){
私有静态最终长serialVersionUID=-4824000127068129154L;
{
put(“罗伯特”、“唐纳德”);
}
};
List employees=Arrays.asList(“Adam”、“James”、“Robert”).stream().map(employeen::new).collect(Collectors.toList());
employees=employees.stream().map(emp->{
if(dict.containsKey(emp.getFirstName())){
emp.setFirstName(dict.get(emp.getFirstName());
}
返回emp;
}).collect(Collectors.toList());
employees.stream().forEach(System.out::println);
}
}
empList=(ArrayList)empList.stream()
.filter(emp->emp.getFirstName().equalsIgnoreCase(“Robert”))
.peek(emp->emp.setFirstName(“罗纳德”))
.collect(Collectors.toList());
当您想要更改原始列表时,将收集的列表分配给原始列表两个不同的返回如何编译?需要确保emp.setName(“ronald”)
返回Employee
对象。(这不符合一般的setter结构。)对不起,伙计们,我在手机上输入了答案,甚至一次都没有运行。现在正确!但我仍然认为我已经给了@user一个想法,他接受了。
list.forEach(e -> {
if (e.firstName.equals("Robert")) {
e.firstName = "Ronald";
}
});
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);
}
}
empList = (ArrayList<Employee>) empList.stream()
.filter(emp -> emp.getFirstName().equalsIgnoreCase("Robert"))
.peek(emp -> emp.setFirstName("Ronald"))
.collect(Collectors.toList());