Skip to content

Instantly share code, notes, and snippets.

@php-coder
Created October 27, 2011 09:37
Show Gist options
  • Save php-coder/1319172 to your computer and use it in GitHub Desktop.
Save php-coder/1319172 to your computer and use it in GitHub Desktop.
Guava Collections2.transform() example
private static Function<Entity, Integer> INVOKE_GET_ID =
new Function<Entity, Integer>() {
@Override
public Integer apply(final Entity entity) {
return entity.getId();
}
};
...
Collection<Integer> ids =
Collections2.transform(entities, INVOKE_GET_ID);
import java.util.Arrays;
import java.util.Collection;
import com.google.common.base.Function;
import com.google.common.collect.Collections2;
class Entity {
private final Integer id;
public Entity(final Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
}
public class GuavaTransform {
public static void main(final String [] args) {
Collection<Entity> entities = Arrays.asList(
new Entity(1),
new Entity(2),
new Entity(3)
);
Collection<Integer> ids = Collections2.transform(
entities,
new Function<Entity, Integer>() {
@Override
public Integer apply(final Entity entity) {
return entity.getId();
}
}
);
System.out.println(ids);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment