Reputation: 86697
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");
?
Upvotes: 5
Views: 2759
Reputation: 26740
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.
Upvotes: 2
Reputation: 140319
Using Java 8:
List<String> names =
foo.getBars().stream().map(Bar::getName).collect(Collectors.toList());
Upvotes: 1
Reputation: 20063
Is there any reason why you couldn't use the MultiMap supplied by Googles collection framework?
This will allow a map with multiple key values.
So you could have a duplicate key (unlike say a hashmap) and return all the values for that key
Then just call get on the associated Map, which would be the same implementation as your expected example of "getAll"
get
Collection get(@Nullable K key) Returns a collection view of all values associated with a key. If no mappings in the multimap have the provided key, an empty collection is returned. Changes to the returned collection will update the underlying multimap, and vice versa.
Parameters: key - key to search for in multimap Returns: the collection of values that the key maps to
Upvotes: -1
Reputation: 3490
Somewhat provides Google guava
List<String> names = new ArrayList(Collections2.transform(foo.getBars(), new Function<Bar,String>() {
String apply(Bar bar) {
return bar.getName()
}
});
Upvotes: 1