Lambda表达式和Stram流组合在遍历循环对象的时候的高效用法
People类
public class People {
private String id;
private String name;
private String years;
private String school;
private String office;
private String pet;
public People(String id, String name, String years, String school, String office, String pet) {
this.id = id;
this.name = name;
this.years = years;
this.school = school;
this.office = office;
this.pet = pet;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getYears() {
return years;
}
public void setYears(String years) {
this.years = years;
}
public String getSchool() {
return school;
}
public void setSchool(String school) {
this.school = school;
}
public String getOffice() {
return office;
}
public void setOffice(String office) {
this.office = office;
}
public String getPet() {
return pet;
}
public void setPet(String pet) {
this.pet = pet;
}
}
Student类
public class Student {
private String id;
private String name;
private String years;
private String school;
private String pet;
public Student(String id, String name, String years, String school, String pet) {
this.id = id;
this.name = name;
this.years = years;
this.school = school;
this.pet = pet;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getYears() {
return years;
}
public void setYears(String years) {
this.years = years;
}
public String getSchool() {
return school;
}
public void setSchool(String school) {
this.school = school;
}
public String getPet() {
return pet;
}
public void setPet(String pet) {
this.pet = pet;
}
}
Main主类:把people类的集合遍历成Student类集合
public class Main {
public static void main(String[] args) {
List<People> peopleList = new ArrayList<>();
List<Student> students = new ArrayList<>();
//把多个People对象遍历成Student对象,
//使用Stream流和Lambda表达式组合 7行
students = peopleList.stream().map(p -> new Student(
p.getId(),
p.getName(),
p.getYears(),
p.getSchool(),
p.getPet()
)).collect(Collectors.toList());
//使用For循环 10行
for (int i = 0;i<peopleList.size();i++){
Student student = new Student(
peopleList.get(i).getId(),
peopleList.get(i).getName(),
peopleList.get(i).getYears(),
peopleList.get(i).getSchool(),
peopleList.get(i).getPet()
);
students.add(student);
}
}
}
通过上面的简单示例,不难看出Lambda表达式和Stream流组合的优势,更少的代码行数以及更少的性能。
只要目标对象有对应的构造函数,就可以使用这种方法进行遍历。
如果使用传统的for循环进行遍历,不仅新增了一个变量i用于循环控制,同时也需要创建多个目标对象,严重浪费内存。