集合中元素属性添加到另一个集合优化
代码在线
最近看项目代码看到如下的代码,准备对代码从可读性进行优化
List<CustomerMappingVo> handleList(List<CustomerMappingVo> list){
List<String> inventoryClassList = Lists.newArrayList();
list.forEach(vo -> inventoryClassList.add(vo.getInvClass()));
List<InventoryClass> inventoryClassNameList = inventoryClassMapper.findCInvCNameByCInvCCode(inventoryClassList);
存在问题:
定义了过多的变量,代码可读性很差
使用jdk1.8的stream流进行优化
需求:收集员工的姓名为一个list集合
package com.shaoming;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author shaoming
* @description
* @date: 2021/8/20 10:36
*/
public class StreamofMapMethodTest {
public static void main(String[] args) {
/**
* 优化后的代码,使用jdk1.8 stream的映射map方法进行优化
*/
List<Employee> employeeList = new StreamofMapMethodTest().getData();
List<String> empNameList = employeeList.stream()
.map(employee -> employee.getEmpName())
.collect(Collectors.toList());
System.out.println(empNameList);
/**
* 优化前的代码,普通的迭代器方式进行遍历
(没有使用foreach进行遍历,因为foreach底层使用的还是迭代器)
*/
List<Employee> employeeList1 = new StreamofMapMethodTest().getData();
List<String> empNameList1 = new ArrayList<>();
Iterator<Employee> iterator = employeeList1.iterator();
while(iterator.hasNext()){
Employee employee = iterator.next();
String empName = employee.getEmpName();
empNameList1.add(empName);
}
System.out.println(empNameList1);
}
public List<Employee> getData(){
List<Employee> employeeList = new ArrayList<Employee>();
for (int i = 0 ; i < 5 ; i++) {
Employee employee = new Employee();
employee.setId(i);
employee.setEmpName("name"+i);
employeeList.add(employee);
}
return employeeList;
}
class Employee{
private Integer id;
private String empName;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", empName='" + empName + '\'' +
'}';
}
}
}
直接运行上面代码即可
总结
建议使用jdk1.8 stream的映射map方法,代码简洁,可读性高