问题
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");?
回答1:
Using Java 8:
List<String> names =
foo.getBars().stream().map(Bar::getName).collect(Collectors.toList());
回答2:
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.
回答3:
Somewhat provides Google guava
List<String> names = new ArrayList(Collections2.transform(foo.getBars(), new Function<Bar,String>() {
String apply(Bar bar) {
return bar.getName()
}
});
回答4:
Is there any reason why you couldn't use the MultiMap supplied by Googles collection framework?
MultiMap
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
来源:https://stackoverflow.com/questions/14710574/how-to-extract-all-elements-of-a-specific-property-in-a-list