简体   繁体   中英

Create new List in Java extracting only one field

I have the following class:

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

At a certain point of my code, I build a list of Person:

List<Person> people = getPeople();

What I need is to create a new List only with the field id of the original list. Of course I can iterate over the list and create a new one:

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

But I wonder if there is a way to do this without iterating.

I am using JDK6.

Thank you very much in advance

It depends what you need to do with the List . If you are happy for it to be a view of the original list's ids that you cannot modify directly, you can do this:

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

If you need an ArrayList of ids, then you are going to have to iterate.

In Java8:

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

EDIT Sorry haven't noticed JDK version.

For J6 + Guava it would be:

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

You can obviously extract the Function to some static variable to make it clearer.

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

Just dumping idea here.

Why not add the id straight into the list when your code adds the person object to the list? This is so that ur id list is maintained on the fly and u won't have to loop through the person list to create a list of id at the end?

Please let me know if I am not understanding your question fully

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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