Let's say I have a bean like below.
class Customer{
private String code;
private String name;
private Integer value;
//getters setters omitted for brevity
}
Then from a method I get a List<Customer>
back. Now let's say I want to get a list of all member "name" from the List. Obviously I can traverse and build a List<String>
of element "name" myself.
However, I was wondering if there is a short cut or more effiecient way to this technique that anyone knows . For instance, if I want to get a list of all keys in a Map object I get do map.keySet(). Something along that line is what I am trying to find out.
Guava has Lists.transform
that can transform a List<F>
to a List<T>
, using a provided Function<F,T>
(or rather, Function<? super F,? extends T>
).
From the documentation:
public static <F,T> List<T> transform( List<F> fromList, Function<? super F,? extends T> function )
Returns a list that applies
function
to each element offromList
. The returned list is a transformed view offromList
; changes tofromList
will be reflected in the returned list and vice versa.The
function
is applied lazily, invoked when needed.
Similar live-view transforms are also provided as follows:
Iterables.transform
(Iterable<F>
to Iterable<T>
)Iterators.transform
(Iterator<F>
to Iterator<T>
)Collections2.transform
(Collection<F>
to Collection<T>
)Maps.transformValues
(Map<K,V1>
to Map<K,V2>
)Looks like you're looking for the Java equivalent of Perl's map
function. This kind of thing might be added to the collections library once (if) Java receives closures. Until then, I think this is the best you can do:
List<String> list = new ArrayList<String>(customers.size());
for ( Customer c : customers ) {
list.add(c.getName());
}
You could also write a map
function that uses a simple interface to provide the mapping function. Something like this:
public interface Transform<I, O> {
O transform(I in);
}
public <I, O> List<O> map(Collection<I> coll, Transform<? super I, ? extends O> xfrm) {
List<O> list = new ArrayList<O>(coll.size());
for ( I in : coll ) {
list.add(xfrm.transform(in));
}
return list;
}
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