Java 8将员工名字从Robert更改为Ronald并返回原始列表

问题描述 投票:-2回答:4
Employee {
    String firstName;
     // Few other fields here
} 

e1.firstName = Robert
e2.firstName = Donald

数组列表中有15个这样的对象

我想更改原始列表

无论firstName是Robert,它都会使用java 8 API成为Ronald

java java-8
4个回答
2
投票
Emplist.stream().map((emp)->{
If(emp.getName().equals("robert")){
emp.setName("ronald") ;
return emp;
}else{
return emp;}}).collect(Collectors.toList());

0
投票

一个简单的forEach版本(忽略get / set方法)

 list.forEach(e -> {
     if (e.firstName.equals("Robert")) {
        e.firstName = "Ronald";
     }
 });

0
投票

您可以填充要转换为的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);
    }
}

0
投票
empList = (ArrayList<Employee>) empList.stream()
            .filter(emp -> emp.getFirstName().equalsIgnoreCase("Robert"))
            .peek(emp -> emp.setFirstName("Ronald"))
            .collect(Collectors.toList());

如果要更改原始列表,请将收集的列表分配给原始列表

© www.soinside.com 2019 - 2024. All rights reserved.