參考;https://blog.csdn.net/icarusliu/article/details/79495534
例子1:
public static void testflatmap(){ Stream<String> s = Stream.of("test", "t1", "t2", "teeeee", "aaaa"); s.flatMap(n -> Stream.of(n.split(""))).forEach(System.out::println); } /** * BiFunction<Integer,Integer,Integer> 兩個輸入參數Integer,Integer ,一個輸出參數 * 有輸入,輸出 (x,y)->x+y */ public static Integer testfuntion(BiFunction<Integer,Integer,Integer> f, int a, int b){ return f.apply(a,b); } /** *一個輸入,一個輸出參數 */ public static Integer testfuntion2(Function<Integer,Integer> f, int a){ return f.apply(a); } /** *一個輸入,沒有輸出 Consumer (x)->x*4 * @param f * @param a * @return */ public static void testfuntion3(Consumer<Integer> f, int a){ f.accept(a); } /** * 2個輸入,沒有輸出 BiConsumer (x,y)->print(x+y) * @return */ public static void testfuntion3(BiConsumer<Integer,Integer> f, int a,int b){ f.accept(a,b); } public static void main(String[] args) { // consumerTest(); // testflatmap(); Integer result = testfuntion((x, y) -> x + y, 1, 3); System.out.println(result); }
Java函數式接口:
1 Consumer
Consumer是一個函數式編程接口; 顧名思義,Consumer的意思就是消費,即針對某個東西我們來使用它,因此它包含有一個有輸入而無輸出的accept接口方法;
除accept方法,它還包含有andThen這個方法;
其定義如下:
default Consumer<T> andThen(Consumer<? super T> after) { Objects.requireNonNull(after); return (T t) -> { accept(t); after.accept(t); }; }
可見這個方法就是指定在調用當前Consumer后是否還要調用其它的Consumer;
使用示例:
public static void consumerTest() { Consumer f = System.out::println; Consumer f2 = n -> System.out.println(n + "-F2"); //執行完F后再執行F2的Accept方法 f.andThen(f2).accept("test"); //連續執行F的Accept方法 f.andThen(f).andThen(f).andThen(f).accept("test1"); }
2 Function
Function也是一個函數式編程接口;它代表的含義是“函數”,而函數經常是有輸入輸出的,因此它含有一個apply方法,包含一個輸入與一個輸出;
除apply方法外,它還有compose與andThen及indentity三個方法,其使用見下述示例;
/** * Function測試 */ public static void functionTest() { Function<Integer, Integer> f = s -> s++; Function<Integer, Integer> g = s -> s * 2; /** * 下面表示在執行F時,先執行G,並且執行F時使用G的輸出當作輸入。 * 相當於以下代碼: * Integer a = g.apply(1); * System.out.println(f.apply(a)); */ System.out.println(f.compose(g).apply(1)); /** * 表示執行F的Apply后使用其返回的值當作輸入再執行G的Apply; * 相當於以下代碼 * Integer a = f.apply(1); * System.out.println(g.apply(a)); */ System.out.println(f.andThen(g).apply(1)); /** * identity方法會返回一個不進行任何處理的Function,即輸出與輸入值相等; */ System.out.println(Function.identity().apply("a")); }
3 Predicate
Predicate為函數式接口,predicate的中文意思是“斷定”,即判斷的意思,判斷某個東西是否滿足某種條件; 因此它包含test方法,根據輸入值來做邏輯判斷,其結果為True或者False。
它的使用方法示例如下:
/** * Predicate測試 */ private static void predicateTest() { Predicate<String> p = o -> o.equals("test"); Predicate<String> g = o -> o.startsWith("t"); /** * negate: 用於對原來的Predicate做取反處理; * 如當調用p.test("test")為True時,調用p.negate().test("test")就會是False; */ Assert.assertFalse(p.negate().test("test")); /** * and: 針對同一輸入值,多個Predicate均返回True時返回True,否則返回False; */ Assert.assertTrue(p.and(g).test("test")); /** * or: 針對同一輸入值,多個Predicate只要有一個返回True則返回True,否則返回False */ Assert.assertTrue(p.or(g).test("ta")); }