Consumer
两个方法
void accept(T t) 执行给定参数
default Consumer andThen(Consumer<? super T> after) 合并两个Consumer
@FunctionalInterface
public interface Consumer<T> {
/**
* Performs this operation on the given argument.
*
* @param t the input argument
*/
void accept(T t);
default Consumer<T> andThen(Consumer<? super T> after) {
Objects.requireNonNull(after);
return (T t) -> { accept(t); after.accept(t); };
}
}
Example
package com.Akmf.functionDemo;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
public class ConsumerDemo {
public static void main(String[] args) {
List<String> list = Arrays.asList("a", "b");
// forEach(list, s -> System.out.println(s));
forEach(list, System.out::println);
ConsumerAccept();
ConsumeraddThen();
}
public static void ConsumerAccept(){
// Consumer to display a number
Consumer<Integer> display = a -> System.out.println(a);
// Implement display using accept()
display.accept(10);
// Consumer to multiply 2 to every integer of a list
Consumer<List<Integer> > modify = list ->
{
for (int i = 0; i < list.size(); i++)
list.set(i, 2 * list.get(i));
};
// Consumer to display a list of numbers
Consumer<List<Integer> >
dispList = list -> list.stream().forEach(a -> System.out.print(a + " "));
List<Integer> list = new ArrayList<>();
list.add(2);
list.add(1);
list.add(3);
// Implement modify using accept()
modify.accept(list);
// Implement dispList using accept()
dispList.accept(list);
System.out.println();
}
public static void ConsumeraddThen(){
// Consumer to multiply 2 to every integer of a list
Consumer<List<Integer> > modify = list ->
{
for (int i = 0; i <= list.size(); i++)
list.set(i, 2 * list.get(i));
};
// Consumer to display a list of integers
Consumer<List<Integer> >
dispList = list -> list.stream().forEach(a -> System.out.print(a + " "));
List<Integer> list = new ArrayList<Integer>();
list.add(2);
list.add(1);
list.add(3);
// using addThen()
// 先dispList 然后modify
try {
dispList.andThen(modify).accept(list);
}
catch (Exception e) {
System.out.println("Exception: " + e);
}
// using addThen()
try {
dispList.andThen(modify);
}
catch (Exception e) {
System.out.println("Exception: " + e);
}
}
public static void forEach(List<String> list,
Consumer<String> consumer){
for(String s : list){
consumer.accept(s);
}
}
}
BiConsumer
两个参数 没有返回值
@FunctionalInterface
public interface BiConsumer<T, U> {
void accept(T t, U u);
default BiConsumer<T, U> andThen(BiConsumer<? super T, ? super U> after) {
Objects.requireNonNull(after);
return (l, r) -> {
accept(l, r);
after.accept(l, r);
};
}
}
Example
package com.Akmf.functionDemo;
import java.util.ArrayList;
import java.util.List;
import java.util.function.BiConsumer;
public class BiConsumerDemo {
public static void main(String[] args) {
BiConsumerAccept();
BiConsumerAndThen();
}
public static void BiConsumerAccept(){
// Create the first list
List<Integer> lista = new ArrayList<Integer>();
lista.add(2);
lista.add(1);
lista.add(3);
// Create the second list
List<Integer> listb = new ArrayList<Integer>();
listb.add(2);
listb.add(1);
listb.add(2);
// BiConsumer to compare both lists
BiConsumer<List<Integer>, List<Integer> >
equals = (list1, list2) ->
{
if (list1.size() != list2.size()) {
System.out.println("False");
}
else {
for (int i = 0; i < list1.size(); i++)
if (list1.get(i) != list2.get(i)) {
System.out.println("False");
return;
}
System.out.println("True");
}
};
equals.accept(lista, listb);
}
public static void BiConsumerAndThen(){
List<Integer> lista = new ArrayList<Integer>();
lista.add(2);
lista.add(1);
lista.add(3);
List<Integer> listb = new ArrayList<Integer>();
listb.add(2);
listb.add(1);
listb.add(2);
BiConsumer<List<Integer>, List<Integer> > equals = (list1, list2) ->
{
if (list1.size() != list2.size()) {
System.out.println("False");
}
else {
for (int i = 0; i < list1.size(); i++)
if (list1.get(i) != list2.get(i)) {
System.out.println("False");
return;
}
System.out.println("True");
}
};
try {
equals.andThen(null).accept(lista, listb);
}
catch (Exception e) {
System.out.println("Exception : " + e);
}
}
}
Predicate
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
default Predicate<T> and(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) && other.test(t);
}
default Predicate<T> negate() {
return (t) -> !test(t);
}
default Predicate<T> or(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) || other.test(t);
}
static <T> Predicate<T> isEqual(Object targetRef) {
return (null == targetRef)
? Objects::isNull
: object -> targetRef.equals(object);
}
}
Example
package com.Akmf.functionDemo;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
/**
*
*
* boolean test(T t);
* Evaluates this predicate on the given argument.
* 根据给定参数评估这个预测
*
*
* static <T> Predicate<T> isEqual(Object targetRef)
* 调用Object.equals()方法进行比较
*
* default Predicate<T> and(Predicate<? super T> other)
* 逻辑与
* other为空 throw new NullPointerException()
* 对两个Predicate 都执行test
* return a composed predicate
*
* default Predicate<T> negate()
* 返回该Predicate的否定 (取反)
*
* default Predicate<T> or(Predicate<? super T> other)
* 逻辑或
* other为空 throw new NullPointerException()
* return a composed predicate
*/
public class PredicateDemo {
public static void main(String[] args) {
PredicateTest();
PredicateAnd();
PredicateOr();
PredicateInFunctionin(10, (i) -> i > 7);
PredicateOnColletion();
}
public static void PredicateTest(){
Predicate<String> checkLength =
str->str.length() > 5;
System.out.println(checkLength.test("das")); //
// false 长度不大于5
}
public static void PredicateAnd(){
Predicate<Integer> greaterThanTen = (i) -> i > 10;
// Creating predicate
Predicate<Integer> lowerThanTwenty = (i) -> i < 20;
boolean result = greaterThanTen.and(lowerThanTwenty).test(15);
System.out.println(result); // true 15 > 10 && 15 < 20
// Calling Predicate method
boolean result2 = greaterThanTen.and(lowerThanTwenty).negate().test(15);
System.out.println(result2); // fale 取反
}
public static Predicate<String> hasLengthOf10 = new Predicate<String>() {
@Override
public boolean test(String t)
{
return t.length() > 10;
}
};
public static void PredicateOr(){
Predicate<String> containsLetterA = p -> p.contains("A");
String containsA = "And";
boolean outcome = hasLengthOf10.or(containsLetterA).test(containsA);
System.out.println(outcome); // true And长度不大于10但是包含A
}
public static void PredicateInFunctionin(int number, Predicate<Integer> predicate)
{
if (predicate.test(number)) {
System.out.println("Number " + number);
}
}
public static class User {
String name, role;
User(String a, String b) {
name = a;
role = b;
}
String getRole() {return role;}
String getName() {return name;}
public String toString() {
return "User Name : " + name + ", Role :" + role;
}
}
public static void PredicateOnColletion(){
List<User> users = new ArrayList<User>();
users.add(new User("John", "admin"));
users.add(new User("Peter", "member"));
List<User> admins = process(users, (User u) -> u.getRole().equals("admin"));
System.out.println(admins);
}
public static List<User> process(List<User> users,
Predicate<User> predicate)
{
List<User> result = new ArrayList<User>();
for (User user: users)
if (predicate.test(user))
result.add(user);
return result;
}
}
Supplier
不需要任何参数 但是会产生一个参数
@FunctionalInterface
public interface Supplier<T> {
/**
* Gets a result.
*
* @return a result
*/
T get();
}
Example
package com.Akmf.functionDemo;
import java.util.Random;
import java.util.function.Supplier;
public class SupplierDemo {
public static void main(String[] args) {
SupplierGet();
}
public static void SupplierGet(){
// This function returns a random value.
Random random = new Random();
Supplier<Integer> randomValue = () -> random.nextInt();
// Print the random value using get()
System.out.println(randomValue.get());
}
}
Function
It represents a function which takes in one argument and produces a result
接受一个参数 生成一个结果
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
Objects.requireNonNull(before);
return (V v) -> apply(before.apply(v));
}
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t) -> after.apply(apply(t));
}
static <T> Function<T, T> identity() {
return t -> t;
}
}
Example
package com.Akmf.functionDemo;
import java.util.function.Function;
/**
* R apply(T t)
* 接受参数t 返回R
*
* default <V> Function<T, V> andThen(Function<? super R, ? extends V> after)
* 如果after为null throw new NullPointerException()
* 先执行自己 再执行after
* 合并成一个Function
*
* default <V> Function<V, R> compose(Function<? super V, ? extends T> before)
* 如果before为null throw new NullPointerException()
* 先执行before 再执行自己
* 合并成一个Function
*
* static <T> Function<T, T> identity()
* Returns a function that always returns its input argument.
* 输出返回输入
*/
public class FunctionDemo {
public static void main(String[] args) {
FunctionApply();
FunctionAddThen();
FunctionCompose();
FunctionIdentity();
}
public static void FunctionApply() {
Function<Integer, Double> half = a -> a / 2.0;
System.out.println(half.apply(10));
}
public static void FunctionAddThen() {
Function<Integer, Double> half = a -> a / 2.0;
try {
half = half.andThen(a -> 3 * a);
}catch (Exception e) {
System.out.println("Exception thrown "
+ "while passing null: "
+ e);
}
System.out.println(half.apply(10));
}
public static void FunctionCompose(){
Function<Integer, Double> half = a -> a / 2.0;
half = half.compose(a -> 3 * a);
System.out.println(half.apply(5));
}
public static void FunctionIdentity(){
Function<Integer, Integer> i = Function.identity();
System.out.println(i.apply(10));
}
}