Reputation: 13666
Suppose that you have a class A
like follows:
public class A{
private B b;
public B getB(){return b;}
}
Then, you have a list of A
objects and you want to create another list that contains the related B
objects, i.e.
List<A> listOfA=...
List<B> listOfB = extractFrom(listOfA, "getB");
Exists a library that does the magic described by function extractFrom
? Maybe it uses reflection, I don't know.
Or, maybe the library relies on an Extractor
interface that uses generics, e.g.
public interface Extractor<T,V>{
public T extract(V source);
}
and then one does:
Extractor ex=...;
List<B> listOfB = extractFrom(listOfA, ex);
PS: The title is horrible! Please, edit the title so that it becomes more meaningfull.
Upvotes: 1
Views: 81
Reputation: 19128
This is know as map.
Here in SO have an answer
In addition you can do with the apache commons using transformers
By example:
Collection<B> bs = CollectionUtils.collect(collectionOfA, new Transformer() {
public Object transform(Object a) {
return ((A) a).getB();
}
});
Upvotes: 1
Reputation: 121710
There is a solution. This uses Guava.
You need a Function<A, B>
, then apply that function using Lists.transform()
:
final Function extractB = new Function<A, B>()
{
@Override
public B apply(final A input)
{
return input.getB();
}
}
// And then:
final List<B> listOfB = Lists.transform(listOfA, extractB);
Note that Java 8 will have Function
, among other niceties "invented" by Guava (Predicate
is another example).
Upvotes: 4