Search code examples
javacollectionsguava

Better way of getting a list of ids


This is the sample object i have

public class Dummy {
    private long id;
    private String name;
    /**
     * @return the id.
     */
    public long getId() {
        return id;
    }
    /**
     * @param id the id to set.
     */
    public void setId(long id) {
        this.id = id;
    }
    /**
     * @return the name.
     */
    public String getName() {
        return name;
    }
    /**
     * @param name the name to set.
     */
    public void setName(String name) {
        this.name = name;
    }

}

My problem is this I have a list of these objects and I need to fetch the list of ids present in that object inside the list. I could easily do this by

List<Long> ids = Lists.newArrayList();
for(Dummy dummy: dummyList){
 ids.add(dummy.getId()); 
}

I am wondering if it can be done by using alternative approach(instead of using a for loop may be?) than what i have come up with may be using Iterables or Collections filtering?

EDIT: I am interested in knowing how it can be done differently than i have come up with.


Solution

  • Using Guava

    You can use Iterables.transform to obtain an Iterable of your indices:

    List<Dummy> dummyList = Lists.newArrayList();
    Iterable<Long> idList = Iterables.transform(dummyList, new Function<Dummy, Long>() {
        public Long apply(Dummy dummy) { return dummy.getId(); };
    });
    

    But it seems really overkill for that. You gain one line and you lose in readability.

    Using Java 8

    Since Java 8 you have closure and you are able to write this in a terser way.

    List<Long> idList = dummyList
                .stream()
                .map(Dummy::getId)
                .collect(Collectors.toList());