Created
October 31, 2013 20:45
-
-
Save gaul/7256843 to your computer and use it in GitHub Desktop.
Demonstrate mapping and filtering using Java 7, Guava, and Java 8 constructs.
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
/** | |
* Demonstrate mapping and filtering using Java 7, Guava, and Java 8 constructs. | |
* | |
* Test with: | |
* javac -cp .:$HOME/.m2/repository/com/google/guava/guava/15.0/guava-15.0.jar MapFilterTest.java | |
*/ | |
import java.util.Collection; | |
import java.util.Iterator; | |
import com.google.common.base.Function; | |
import com.google.common.base.Functions; | |
import com.google.common.base.Predicate; | |
import com.google.common.base.Predicates; | |
import com.google.common.collect.FluentIterable; | |
import com.google.common.collect.Lists; | |
public class MapFilterTest { | |
/** Java 7 imperative style. */ | |
private static Iterator<String> testImperative( | |
Collection<Object> objects) { | |
Collection<String> strings = Lists.newArrayList(); | |
for (Object object : objects) { | |
if (object != null) { | |
strings.add(object.toString()); | |
} | |
} | |
return strings.iterator(); | |
} | |
/** Guava functional programming (without helpers). */ | |
private static Iterator<String> testFluentIterable( | |
Collection<Object> objects) { | |
return FluentIterable.from(objects) | |
.filter(new Predicate<Object>() { | |
@Override | |
public boolean apply(Object object) { | |
return object != null; | |
} | |
}).transform(new Function<Object, String>() { | |
@Override | |
public String apply(Object object) { | |
return object.toString(); | |
} | |
}).iterator(); | |
} | |
/** Guava functional programming (with helpers). */ | |
private static Iterator<String> testFluentIterableWithHelpers( | |
Collection<Object> objects) { | |
return FluentIterable.from(objects) | |
.filter(Predicates.notNull()) | |
.transform(Functions.toStringFunction()) | |
.iterator(); | |
} | |
/** Java 8 functional style. */ | |
private static Iterator<String> testLambda( | |
Collection<Object> objects) { | |
return objects.stream() | |
.filter(object -> object != null) | |
.map(Object::toString) | |
.iterator(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment