Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a list of elements from an ArrayList

Tags:

java

arraylist

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.

like image 859
CoolBeans Avatar asked Jun 24 '10 17:06

CoolBeans


2 Answers

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 of fromList. The returned list is a transformed view of fromList; changes to fromList 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>)
like image 65
polygenelubricants Avatar answered Oct 03 '22 11:10

polygenelubricants


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;
}
like image 45
Mark Peters Avatar answered Oct 03 '22 11:10

Mark Peters