猿问

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

Employee {

    String firstName;

     // Few other fields here


e1.firstName = Robert

e2.firstName = Donald

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


我想更改原始列表,以便


凡 firstName 是 Robert 它使用 java 8 API 变成 Ronald


炎炎设计
浏览 103回答 4
4回答

慕侠2389804

Emplist.stream().map((emp)->{If(emp.getName().equals("robert")){emp.setName("ronald") ;return emp;}else{return emp;}}).collect(Collectors.toList());

UYOU

empList&nbsp;=&nbsp;(ArrayList<Employee>)&nbsp;empList.stream() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.filter(emp&nbsp;->&nbsp;emp.getFirstName().equalsIgnoreCase("Robert")) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.peek(emp&nbsp;->&nbsp;emp.setFirstName("Ronald")) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.collect(Collectors.toList());由于您想更改原始列表,请将收集的列表分配给原始列表

温温酱

一个简单的 forEach 版本(get/set 方法被忽略)&nbsp;list.forEach(e -> {&nbsp; &nbsp; &nbsp;if (e.firstName.equals("Robert")) {&nbsp; &nbsp; &nbsp; &nbsp; e.firstName = "Ronald";&nbsp; &nbsp; &nbsp;}&nbsp;});

RISEBY

您可以填充Map要转换为的名称。import java.util.*;import java.util.stream.Collectors;public class Employee {&nbsp; &nbsp; private String firstName;&nbsp; &nbsp; public String getFirstName() {&nbsp; &nbsp; &nbsp; &nbsp; return firstName;&nbsp; &nbsp; }&nbsp; &nbsp; public void setFirstName(String firstName) {&nbsp; &nbsp; &nbsp; &nbsp; this.firstName = firstName;&nbsp; &nbsp; }&nbsp; &nbsp; public Employee(String firstName) {&nbsp; &nbsp; &nbsp; &nbsp; this.firstName = firstName;&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public String toString() {&nbsp; &nbsp; &nbsp; &nbsp; return String.format("Employee [firstName=%s]", firstName);&nbsp; &nbsp; }&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; Map<String, String> dict = new HashMap<String, String>() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; private static final long serialVersionUID = -4824000127068129154L;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; put("Robert", "Donald");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; &nbsp; List<Employee> employees = Arrays.asList("Adam", "James", "Robert").stream().map(Employee::new).collect(Collectors.toList());&nbsp; &nbsp; &nbsp; &nbsp; employees = employees.stream().map(emp -> {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (dict.containsKey(emp.getFirstName())) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; emp.setFirstName(dict.get(emp.getFirstName()));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return emp;&nbsp; &nbsp; &nbsp; &nbsp; }).collect(Collectors.toList());&nbsp; &nbsp; &nbsp; &nbsp; employees.stream().forEach(System.out::println);&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答