Created
October 27, 2011 09:37
-
-
Save php-coder/1319172 to your computer and use it in GitHub Desktop.
Guava Collections2.transform() example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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