Fork me on GitHub

java.util.function 中的 Function、Predicate、Consumer

函数式接口:

函数式接口(Functional Interface)就是一个有且仅有一个抽象方法,但可以有多个非抽象方法的接口。

函数式接口可以被隐式转换为 Lambda 表达式。

Function 函数

Function 与 BiFunction

输入一个或多个参数,也可以规定返回值类型,并执行一段逻辑

Function<Integer, Integer> function = num -> num + 1;
Function<Integer, Integer> function1 = num -> num * 2;
System.out.println(function.apply(1));      // out:2
System.out.println(function1.compose(function).apply(1));   // out:4
System.out.println(function1.andThen(function).apply(1));   // out:3

BiFunction<Integer, Integer, Long> bF = (i1, i2) -> Long.parseLong(i1+i2+"");
System.out.println(bF.apply(1, 2));      // out:3

DIYBiFunction<Integer, Integer, Integer, Integer> diyBiFunction = (n1,n2,n3) -> n1+n2+n3;
System.out.println(diyBiFunction.apply(1,2,3)); //out:6

public interface DIYBiFunction<T, U, E, R> {
  R apply(T t, U u, E e);
}
public class DIYBiFunctionImpl implements DIYBiFunction {
  @Override
  public Object apply(Object o, Object o2, Object o3) {
    if (o instanceof Integer
        && o2 instanceof Integer
        && o3 instanceof Integer) {
      return (Integer)o + (Integer)o2 + (Integer)o3;
    } else {
      return null;
    }
  }
}

Predicate 谓词:

判断输入的对象是否符合某个条件

BiPredicate

public class BiPredicateTest { 
    public static void main(String[] args) { 
        // 表示一个谓词 
        Predicate<String> p1 = p -> p.length() > 2; 
        System.out.println(p1.test("1")); 
        System.out.println(p1.test("123")); 
 
        BiPredicate<Integer, String> biPredicate = (i , s) -> s.length() > i; 
        System.out.println(biPredicate.test(1, "12")); 
    } 
} 

Consumer :

接收一个参数,并执行一段逻辑

BiConsumer

public class BiConsumerTest { 
    public static void main(String[] args) { 
        Map<Integer, String> map = Maps.newHashMap(); 
        map.put(1, "a"); 
        map.put(2, "b"); 
        map.put(3, "c"); 
        BiConsumer<Integer, String> biConsumer = new BiConsumer<Integer, String>() { 
            @Override 
            public void accept(Integer integer, String s) { 
                System.out.println(String.format("out:%s-%s", integer, s)); 
            } 
        }; 
        map.forEach(biConsumer); 
        map.forEach(new BiC1()); 
        map.forEach(new BiC2()); 
    } 
    private static class BiC1 implements BiConsumer<Integer, String> { 
        @Override 
        public void accept(Integer integer, String s) { 
            System.out.println(String.format("BiC1, out: %s - %s", integer, s)); 
        } 
    } 
    private static class BiC2 implements BiConsumer<Integer, String> { 
        @Override 
        public void accept(Integer integer, String s) { 
            System.out.println(String.format("BiC2, out: %s - %s", integer, s)); 
        } 
    } 
} 

 

posted @ 2018-08-21 20:08  郑斌blog  阅读(4416)  评论(0编辑  收藏  举报