Consumer<T>:包含兩個方法
void accept(T t):對給定的引數執行操作
default Consumer <T> andThen(Consumer after):回傳一個組合的Consumer,依次執行此操作,然后執行after操作
package Demo0512;
?
import java.util.function.Consumer;
?
public class ConsumerDemo {
public static void main(String[] args) {
//呼叫
operatorString("最美不過姑娘你",s-> System.out.println(s));
System.out.println("-----------------------------------------------------------");
//呼叫消費兩個字串
operatorStringtwo("最美不過姑娘你",s-> System.out.println(s),s-> System.out.println(new StringBuilder(s).reverse().toString()));
?
}
//定義一個方法,消費一個字串資料
private static void operatorString(String name, Consumer<String> ca){
ca.accept(name);
}
//定義一個方法,消費兩個個字串資料
private static void operatorStringtwo(String name, Consumer<String> ca,Consumer<String> co){
ca.andThen(co).accept(name);
}
}
練習:
1.定義一個字串陣列String [] name={"張三,30","李四,45","王五,52"};
2.將資訊按照姓名: ;年齡 : ;格式列印
3.要求將列印姓名的動作作為第一個Consumer介面的Lambda實體,將列印年齡的動作作為第二 個Consumer介面的Lambda實體并組合起來
package Demo0512;
import java.util.function.Consumer;
public class ConsumerDemo01 {
public static void main(String[] args) {
//定義一個字串陣列
String[] name = {"張三,15", "李四,56", "王五,56"};
//呼叫方法
stringInfo(name, str -> {
String name1 = str.split(",")[0];
System.out.print("姓名:" + name1);
}, str -> {
int age = Integer.parseInt(str.split(",")[1]);
System.out.println("年齡:" + age);
});
}
//定義一個方法,進行組合操作
private static void stringInfo(String[] name, Consumer<String> cp, Consumer<String> co) {
//遍歷字串陣列
for (String str : name) {
cp.andThen(co).accept(str);
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/472919.html
標籤:其他
下一篇:中科軟測認證中心(隨筆)
