VB_
VB_

Reputation: 45732

Guava Collections2.transform not work

I launch the code below in debugger:

List<MyBean> target = getMyBeans();
Collections2.transform(target, new Function<MyBean, MyBean>() { //BREAKPOINT: target.length equals 4
     @Nullable
     @Override
     public MyBean apply(@Nullable MyBean bean) {
          return removeUnnecessaryProperties(bean); //BREAKPOINT: never invoked
     }
});

Problem: Collections2.transform is never invoked despite target has 4 elements.

Question: Why Collections2.transform is never invoked?

Upvotes: 0

Views: 521

Answers (2)

user3458
user3458

Reputation:

Collections2.transform is a lazy operation.

The documentation says:

The returned collection is a live view of fromCollection; changes to one affect the other.

For that to work, each element must be transformed when it's accessed.

Try using the transformed collection, e.g. iterate through it - then you'll see your transformation method invoked.

Upvotes: 2

ColinD
ColinD

Reputation: 110104

transform returns a new Collection that transforms elements in the underlying collection only as needed. So your Function will be invoked once for each element in target as you iterate the returned Collection, for example.

Judging by your code, what you really want to be doing is much simpler (assuming removeUnnecessaryProperties returns the same object that's passed to it):

for (MyBean bean : target) {
  removeUnnecessaryProperties(bean);
}

Upvotes: 5

Related Questions