gpt4 book ai didi

java - 如何将以下代码片段转换为 Java 8 功能?

转载 作者:行者123 更新时间:2023-12-03 20:44:20 27 4
gpt4 key购买 nike

我有 POJO 员工,其技能列表如下所示:-

public class Skills {

private String language;
private double versions;

public String getLanguage() {
return language;
}

public void setLanguage(String language) {
this.language = language;
}

public double getVersions() {
return versions;
}

public void setVersions(double versions) {
this.versions = versions;
}
}

import java.util.List;

public class Employee {

private long empId;
private String empName;
private String empAddress;
private double salary;
private List<Skills> skills;

public List<Skills> getSkills() {
return skills;
}

public void setSkills(List<Skills> skills) {
this.skills = skills;
}

public long getEmpId() {
return empId;
}

public void setEmpId(long empId) {
this.empId = empId;
}

public String getEmpName() {
return empName;
}

public void setEmpName(String empName) {
this.empName = empName;
}

public String getEmpAddress() {
return empAddress;
}

public void setEmpAddress(String empAddress) {
this.empAddress = empAddress;
}

public double getSalary() {
return salary;
}

public void setSalary(double salary) {
this.salary = salary;
}

@Override
public String toString() {
return "Employee{" +
"empId=" + empId +
", empName='" + empName + '\'' +
", empAddress='" + empAddress + '\'' +
", salary=" + salary +
'}';
}

public Employee(long empId, String empName, String empAddress, double salary, List<Skills> skills) {
this.empId = empId;
this.empName = empName;
this.empAddress = empAddress;
this.salary = salary;
this.skills = skills;
}
}

我正在尝试执行以下操作:-

 List<Employee> javaEmpList = new ArrayList<>();

for (Employee emp : empList) {

for (Skills skill : emp.getSkills()) {

if (skill.getLanguage().equalsIgnoreCase("Java")) {
javaEmpList.add(emp);
}
}
}

我正在尝试使用 Java 8 功能来转换此实现。有人可以帮我吗?我是 Java 8 的新手。我尝试使用 streams + filter + map 组合,但我无法获得结果。

最佳答案

你需要的是StreamList<Employee> , 使用 filter()只保留 Employee具有 Java 技能,并且 collect()过滤后的 Employee进入新的List .

请注意,这与您的嵌套循环的行为并不完全相同,但我假设您真的不想添加相同的 Employee多次输出 List .

List<Employee> javaEmpList =
empList.stream()
.filter(emp -> emp.getSkills()
.stream()
.anyMatch(skill -> skill.getLanguage().equalsIgnoreCase("Java")))
.collect(Collectors.toList());

关于java - 如何将以下代码片段转换为 Java 8 功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58058067/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com