利用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);

}
}



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM