Java 一个数组集合List<People> 赋值给另一个数组集合List<NewPeople> ,两个数组集合属性部分一致。

Java 一个数组集合List 赋值给另一个数组集合List ,两个数组集合属性部分一致。

下面是一个Demo, 具体要根据自己的业务调整。

import java.util.ArrayList;
import java.util.List;

class People {
    private String name;
    private int age;
    private String address;

    public People(String name, int age, String address) {
        this.name = name;
        this.age = age;
        this.address = address;
    }

    // 省略getter和setter方法
}

class NewPeople {
    private String name;
    private int age;

    public NewPeople(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // 省略getter和setter方法
}

public class Main {
    public static void main(String[] args) {
        List<People> peopleList = new ArrayList<>();
        peopleList.add(new People("张三", 30, "北京"));
        peopleList.add(new People("李四", 20, "上海"));
        peopleList.add(new People("王五", 50, "广州"));

        List<NewPeople> newPeopleList = new ArrayList<>();
        for (People people : peopleList) {
            NewPeople newPeople = new NewPeople(people.getName(), people.getAge());
            newPeopleList.add(newPeople);
        }

        // 输出newPeopleList
        for (NewPeople newPeople : newPeopleList) {
            System.out.println("姓名:" + newPeople.getName() + ",年龄:" + newPeople.getAge());
        }
    }
}

你可能感兴趣的:(java,java,list,开发语言,spring,boot)