Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

how can I best get all "name" string elements of the following structure:

class Foo {
    List<Bar> bars;
}

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

My approach would be:

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

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

This might work, but isn't there something in java.Collections where I just can write like this: Collections.getAll(foo.getBars(), "name");?

like image 380
membersound Avatar asked Oct 06 '22 03:10

membersound


2 Answers

If you use Eclipse Collections and change 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 extract the function as a constant on Bar, it shortens to:

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

With Java 8 lambdas, you don't need the Function at all.

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

If you can't change the return type of getBars(), you can wrap it in a ListAdapter.

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

Note: I am a committer for Eclipse collections.

like image 200
Craig P. Motlin Avatar answered Oct 07 '22 18:10

Craig P. Motlin


Using Java 8:

List<String> names =        
    foo.getBars().stream().map(Bar::getName).collect(Collectors.toList());
like image 22
Andy Turner Avatar answered Oct 07 '22 18:10

Andy Turner