利用jdk8的新特性将一个对象集合转化为其他对象集合的方式
1 以下代码主要利用jdk8中的lambda表达式, 和集合的stream()流
2 建立Person类和Student类,student继承Person
package demo;
public class Person {
private String name;
private Long pId;
public Person() {
}
public Person(String name, Long pId) {
this.name = name;
this.pId = pId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getpId() {
return pId;
}
public void setpId(Long pId) {
this.pId = pId;
}
}
package demo;
public class Student extends Person {
private String schoolName;
private Long sId;
public String getSchoolName() {
return schoolName;
}
public void setSchoolName(String schoolName) {
this.schoolName = schoolName;
}
public Long getsId() {
return sId;
}
public void setsId(Long sId) {
this.sId = sId;
}
@Override
public String toString() {
return this.getName()+"-"+this.getpId()+"-"+this.getSchoolName()+"-"+this.getsId();
}
}
3 建立主函数,测试
package demo;
import org.springframework.beans.BeanUtils;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class demo {
public static void main(String[] args) {
List<Person> persons = Arrays.asList(
new Person("张三", 1L),
new Person("李四", 2L)
);
// 将Peson集合转化为String集合
List<String> strs=persons.stream().map(person -> person.getName()).collect(Collectors.toList());
System.out.println("strs = " + strs);
// 将Person集合转化为Student集合
List<Student> students = persons.stream().map(person -> {
Student student = new Student();
BeanUtils.copyProperties(person, student);
if (person.getName() == "张三") {
student.setSchoolName("三中");
student.setsId(3L);
}
if (person.getName() == "李四") {
student.setSchoolName("四中");
student.setsId(4L);
}
return student;
}).collect(Collectors.toList());
System.out.println("students = " + students);
}
}