Rafael
Rafael

Reputation: 3112

How can I get a list of values for a certain property

I'd like to have a list of values for a certain property of an object inside an ArrayList. Supposing I have a class like this:

public class Foo {
    private String b, a, r;
    //Constructor...
    //Getters...
}

Then I create an ArrayList<Foo>:

ArrayList<Foo> fooList = new ArrayList<>();
fooList.add(new Foo("How", "Hey", "Hey"));
fooList.add(new Foo("Can", "Hey", "Hey"));
fooList.add(new Foo("I", "Hey", "Hey"));
fooList.add(new Foo("Get", "Hey", "Hey"));
fooList.add(new Foo("Those?", "Hey", "Hey"));

In an ArrayList<Foo>, is it possible to get a List of a certain property of Foo without having to iterate over my ArrayList using a for loop? Maybe something simillar to valueforkey in Objective-c. This would make easier to print values using TextUtils.join() if I had an ArrayList<String> containing How, Can, I, Get, and Those.

Upvotes: 0

Views: 62

Answers (1)

shmosel
shmosel

Reputation: 50716

Using Java 8, you can stream, map and collect:

List<String> list = fooList.stream()
        .map(Foo::getProp)
        .collect(Collectors.toList());

If you have Guava, you can get a transformed view of your list like this:

List<String> list = Lists.transform(fooList, Foo::getProp);

The Java 7 version:

List<String> list = Lists.transform(fooList, new Function<Foo, String>() {
    @Override
    public String apply(Foo foo) {
        return foo.getProp();
    }
});

Upvotes: 1

Related Questions