1

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.

3
  • 1
    AFAIK no, there's no such library. Commented Jun 4, 2013 at 14:15
  • Just as a hint: You are looking for the equivalent in Java of Python's map(function, iterable, ...) function, described here: docs.python.org/2/library/functions.html#map Commented Jun 4, 2013 at 14:19
  • Ok, I will implement it from myself. Usually I don't like to reinvent the well! Commented Jun 4, 2013 at 14:19

2 Answers 2

4

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).

Sign up to request clarification or add additional context in comments.

3 Comments

Oh! Great! I was very surprised to discover that none already implemented such a useful utility! Thank you!
Guava is a gold mine. Just Use It(tm) :p
I know, I use it! But I don't know all the utilities. :)
1

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();
    }
});

1 Comment

Yes. I saw a time ago an implementation of apache commons that use generics, but I don't found the link.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.