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

发布时间:2024年01月22日

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());
        }
    }
}
文章来源:https://blog.csdn.net/qq_46703281/article/details/135740160
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。