利⽤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 Name()+"-"+pId()+"-"+SchoolName()+"-"+sId();
}
}
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 -> Name()).List()); System.out.println("strs = " + strs);
// 将Person集合转化为Student集合
List<Student> students = persons.stream().map(person -> {
Student student = new Student();
if (Name() == "张三") {
nodejs字符串转数组student.setSchoolName("三中");
student.setsId(3L);
}
if (Name() == "李四") {
student.setSchoolName("四中");
student.setsId(4L);
}
return student;
}).List());
System.out.println("students = " + students);
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论