Created
November 16, 2016 22:48
-
-
Save andrewrlee/af3d4bb99f125ce68bc1c7c2dcf5ecc0 to your computer and use it in GitHub Desktop.
Predicates
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
package uk.co.optimisticpanda.functionutils.predicates; | |
import java.util.function.Function; | |
import java.util.function.Predicate; | |
public class Predicates { | |
public static <T, U> Predicate<T> has(Function<T, U> f, Predicate<U> p) { | |
return t -> p.test(f.apply(t)); | |
} | |
} |
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
package uk.co.optimisticpanda.functionutils.predicates; | |
import static java.util.Arrays.asList; | |
import static java.util.function.Predicate.isEqual; | |
import static java.util.stream.Collectors.toList; | |
import static org.assertj.core.api.Assertions.assertThat; | |
import static uk.co.optimisticpanda.functionutils.predicates.Predicates.has; | |
import java.util.List; | |
import java.util.function.Predicate; | |
import org.assertj.core.api.AbstractListAssert; | |
import org.assertj.core.api.ObjectAssert; | |
import org.junit.Test; | |
public class PredicatesTest { | |
private final List<Customer> customers = asList( | |
new Customer("sally", 1), | |
new Customer("bob", 2), | |
new Customer("mark", 0)); | |
@Test | |
public void checkHas(){ | |
namesOfCustomersThat(has(Customer::getItemsInBasket, isEqual(1))) | |
.containsExactly("sally"); | |
namesOfCustomersThat(has(Customer::getItemsInBasket, i -> i > 0)) | |
.containsExactly("sally", "bob"); | |
} | |
private AbstractListAssert<?, List<? extends String>, String, ObjectAssert<String>> namesOfCustomersThat(Predicate<Customer> p) { | |
return assertThat(customers.stream().filter(p).map(Customer::getName).collect(toList())); | |
} | |
private static class Customer { | |
private final String name; | |
private final int itemsInBasket; | |
private Customer(String name, int itemsInBasket) { | |
this.name = name; | |
this.itemsInBasket = itemsInBasket; | |
} | |
private String getName() { | |
return name; | |
} | |
private int getItemsInBasket() { | |
return itemsInBasket; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment