天天看點

JAVA8函數式接口--Consumer接口Consumer接口說明使用示例

Consumer接口說明

represents an operation that accepts a single input argument and returns no result. Unlike most other functional interfaces, {@code Consumer} is expected to operate via side-effects

表示一個接受單個輸入參數且不傳回任何結果的操作。與大多數其他功能接口不同,Consumer接口通過副作用進行操作

此接口提供了兩個方法: accept, andThen

JAVA8函數式接口--Consumer接口Consumer接口說明使用示例

使用示例

import java.util.Arrays;
import java.util.function.Consumer;

public class ConsumerInterfaceDemo {
    public static void main(String[] args) {
        String[] arr = {"張三,男","李四,男","王五,男"};
        printInfo(arr,m->{
            String name = m.split(",")[0];
            System.out.print("name:"+name);
        },m->{
            String age = m.split(",")[1];
            System.out.println(",age:"+age);
        });
    }

    public static void printInfo(String[] arr, Consumer<String> consumer1, Consumer<String> consumer2) {
        Arrays.stream(arr).forEach(m -> consumer1.andThen(consumer2).accept(m));
    }

}
           

輸出結果是:

name:張三,age:男

name:李四,age:男

name:王五,age:男