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

weixin_34015860發表於2018-08-21

函式式介面:

函式式介面(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)); 
        } 
    } 
} 

 

相關文章