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

    }
    }


  • 相关阅读:
    ABP之动态WebAPI
    ssh下常用操作汇总(good)
    XP下类似%windir% %userprofile% 的变量的说明(转)
    Cannot update paths and switch to branch at the same time(转)
    git branch(转)
    Git提交代码的处理流程(转)
    Android锁定EditText内容和随机生成验证码
    Android L下载
    vi 命令 使用方法
    Openfire开发配置,Openfire源码配置,OpenFire二次开发配置
  • 原文地址:https://www.cnblogs.com/zxq-Study-Java/p/10040632.html
Copyright © 2011-2022 走看看