zoukankan      html  css  js  c++  java
  • 利用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);

    }
    }


  • 相关阅读:
    诸暨集训游记
    P2678 跳石头
    P1577 切绳子
    P1328 生活大爆炸版石头剪刀布
    P1067 多项式输出
    分解因数
    【管理篇】团队组织与架构演进方法论
    【状态机】行为状体机和协议状态机
    【数据库】分库分表
    【OLAP】从数仓到Kappa架构
  • 原文地址:https://www.cnblogs.com/zxq-Study-Java/p/10040632.html
Copyright © 2011-2022 走看看