Skip to content

Instantly share code, notes, and snippets.

@ingarabr
Created January 10, 2013 20:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ingarabr/4505555 to your computer and use it in GitHub Desktop.
Save ingarabr/4505555 to your computer and use it in GitHub Desktop.
Example on an alternative to hamcrestmatchers http://code.google.com/p/hamcrest-collections/wiki/GettingStarted
package com.abrahams1.guava;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import java.util.List;
import org.junit.Test;
import static com.abrahams1.guava.GuavaIterable.IntegerPredicate.*;
import static com.google.common.collect.Lists.newArrayList;
import static org.hamcrest.core.AllOf.allOf;
import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.assertThat;
import static org.junit.internal.matchers.IsCollectionContaining.hasItems;
public class GuavaIterable {
@Test
public void filterIterables() throws Exception {
List<Integer> list = newArrayList(0, 1, 2, 3, 5, 6, 7, 8, 9);
assertThat(Iterables.filter(list, greaterThan(2)), allOf(hasItems(3, 5, 6, 7, 8, 9), not(hasItems(0, 1, 2))));
assertThat(Iterables.filter(list, lowerThan(2)), allOf(hasItems(0, 1), not(hasItems(3, 5, 6, 7, 8, 9))));
assertThat(Iterables.filter(list, equalTo(2)), allOf(hasItems(2), not(hasItems(0, 1, 3, 5, 6, 7, 8, 9))));
}
public static class IntegerPredicate implements Predicate<Integer> {
private final int value;
private Rule rule;
private enum Rule {GREATER, LOWER, EQUAL}
public static IntegerPredicate greaterThan(int i) {
return new IntegerPredicate(i, Rule.GREATER);
}
public static IntegerPredicate lowerThan(int i) {
return new IntegerPredicate(i, Rule.LOWER);
}
public static IntegerPredicate equalTo(int i) {
return new IntegerPredicate(i, Rule.EQUAL);
}
private IntegerPredicate(int value, Rule rule) {
this.value = value;
this.rule = rule;
}
@Override
public boolean apply(Integer input) {
if (Rule.GREATER == rule) {
return input > value;
} else if (Rule.LOWER == rule) {
return input < value;
}
return value == input;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment