簡體   English   中英

用Java創建新列表僅提取一個字段

[英]Create new List in Java extracting only one field

我有以下課程:

public class Person {
    private Integer id;
    private String name;
    private String address;
    ...
}

在代碼的特定位置,我建立了一個Person列表:

List<Person> people = getPeople();

我需要的是僅使用原始列表的字段id創建一個新列表。 當然,我可以遍歷列表並創建一個新列表:

List<Integer> idsList = new ArrayList<Integer>();
for (Person person: people){
    idsList.add(person.getId());
}

但是我想知道是否有一種方法可以不進行迭代。

我正在使用JDK6。

提前非常感謝你

這取決於您需要使用List做什么。 如果您很高興能夠查看無法直接修改的原始列表的ID,則可以執行以下操作:

public static List<Integer> idList(final List<Person> people) {
    return new AbstractList<Integer>() {
        @Override
        public Integer get(int index) {
            return people.get(index).getId();
        }
        @Override
        public int size() {
            return people.size();
        }
    };
}

如果您需要ID的ArrayList ,則必須進行迭代。

在Java8中:

List<Person> people = getPeople();
List<Integer> ids = people.stream()
    .map(Person::getId)
    .collect(Collectors.toList());

抱歉,尚未注意到JDK版本。

對於J6 + Guava,它將是:

List<Person> people = getPeople();
List<Integer> ids = FluentIterable.from(people)
.transform(new Function<Person, Integer>() {
    @Override
    public Integer apply(Person person) {
        return person.getId();
    }
}).toList();

您顯然可以將Function提取到某個靜態變量中,以使其更加清晰。

private static final Function<Person, Integer> TO_ID = new Function<Person, Integer>() {
    @Override public Integer apply(Person person) {
        return person.getId();
    }
};

public static void main(String [] args) {
    List<Person> people = getPeople();
    List<Integer> ids = FluentIterable.from(people)
            .transform(TO_ID)
            .toList();
}

只是在這里傾銷想法。

當代碼將人員對象添加到列表中時,為什么不直接將id添加到列表中呢? 這樣一來,您的ID列表就可以即時維護,而您又不必遍歷人員列表來最后創建ID列表呢?

如果我沒有完全理解您的問題,請告訴我

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM