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");
?
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.
Using Java 8:
List<String> names =
foo.getBars().stream().map(Bar::getName).collect(Collectors.toList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With