简体   繁体   English

从ArrayList对象中检索值的array []

[英]Retrieve array[] of values from ArrayList of objects

Let's say I have an ArrayList of objects. 假设我有一个对象的ArrayList。 For example: ArrayList<Person> personList , where each Person has 2 class variables String name and int age . 例如: ArrayList<Person> personList ,其中每个Person有2个类变量String nameint age These variables each have their own getter methods getName() and getAge() . 这些变量每个都有自己的getter方法getName()getAge()

What is the simplest way to retrieve an array (or ArrayList) of int ages[] ? 检索int ages[]的数组(或ArrayList)的最简单方法是什么?

Note this question is similar to the verbosely titled " Retrieve an array of values assigned to a particular class member from an array of objects in java ", though without the arbitrary restriction on for-loops, and using an ArrayList instead of an Array. 请注意,此问题类似于详细标题为“ 从java中的对象数组中检索分配给特定类成员的值数组 ”,尽管没有对for循环的任意限制,并且使用ArrayList而不是Array。

创建与列表大小相同的目标数组,然后遍历列表并将每个元素的age添加到目标数组。

Numerous ways to do this -- here is one. 有很多方法可以做到这一点 - 这是一个。

First get the ages into a list (using a java8 stream), and then convert the list into an array. 首先将年龄放入列表(使用java8流),然后将列表转换为数组。

public int[] getAges() {
    return personList.stream()
        .mapToInt(Person::getAge)
        .toArray();
}
Person P1 = new Person("Dev", 25);
Person P2 = new Person("Andy", 12);
Person P3 = new Person("Mark", 20);
Person P4 = new Person("Jon", 33);

ArrayList<Person> personList = new ArrayList<>(Arrays.asList(new Person[] { P1, P2, P3, P4 }));
int[] ages = getPersonAges(personList); // [25, 12, 20, 33]

private static int[] getPersonAges(ArrayList<Person> personList) {
    int[] ages = new int[personList.size()];
    int idx = 0;

    for (Person P : personList) {    // Iterate through the personList
        int age = P.getAge();
        ages[idx++] = age;
    }

    return ages;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM