How to extract all elements of a specific property to a list?

what is the best way to get all the "names" of string elements of the following structure:

class Foo {
    List<Bar> bars;
}

class Bar {
    private String name;
    private int age;
}

My approach:

List<String> names = new ArrayList<String>();

for (Bar bar : foo.getBars()) {
    names.add(bar.getName());
}

This might work, but there is nothing in java. Collectionswhere I can simply write like this Collections.getAll(foo.getBars(), "name");:?

+5
source share
4 answers

Using Java 8:

List<String> names =        
    foo.getBars().stream().map(Bar::getName).collect(Collectors.toList());
+1
source

If you use Eclipse Collections and modify getBars () to return a MutableList or something similar, you can write:

MutableList<String> names = foo.getBars().collect(new Function<Bar, String>()
{
    public String valueOf(Bar bar)
    {
        return bar.getName();
    }
});

If you retrieve a function as a constant in Bar, it is reduced to:

MutableList<String> names = foo.getBars().collect(Bar.TO_NAME);

With Java 8 lambdas, you don't need a function at all.

MutableList<String> names = foo.getBars().collect(Bar::getName);

getBars(), ListAdapter.

MutableList<String> names = ListAdapter.adapt(foo.getBars()).collect(Bar.TO_NAME);

. Eclipse.

+3

Google guava

List<String> names = new ArrayList(Collections2.transform(foo.getBars(), new Function<Bar,String>() {
    String apply(Bar bar) {
        return bar.getName()
    }
});
+1

- , MultiMap, Googles?

MultiMap

.

, ( -)

get , , "getAll"

Collection get (@Nullable K) Returns a collection view of all the values ​​associated with the key. If no mappings in the multimar have provided that key, an empty collection is returned. Changes to the return collection will update the base multimar and vice versa.

Parameters: key - the key to search in multimap Returns: a set of values ​​that the key maps to

-1
source

All Articles