JavaSE-23.1.3【常用函数式接口之Consumer、Consumer案例-按要求打印信息】
1 package day14.lesson1; 2 3 import java.util.function.Consumer; 4 5 /* 6 1.6 常用函数式接口之Consumer 7 8 Consumer接口 9 Consumer<T>接口也被称为消费型接口,它消费的数据的数据类型由泛型T指定 10 11 常用方法 12 void accept(T t) 对给定的参数执行此操作 13 default Consumer andThen(Consumer after) 返回一个组合的Consumer,依次执行此操作,然后执行after操作 14 */ 15 public class Demo6Consumer { 16 public static void main(String[] args) { 17 // Lambda表达式 18 /*operatorStr("tom", (String s) -> { 19 System.out.println(s); 20 });*/ 21 operatorStr("tom", s -> System.out.println(s)); // tom 22 /*operatorStr("tom", s->{ 23 StringBuilder sb = new StringBuilder(s); 24 StringBuilder reverse = sb.reverse(); 25 String ss = reverse.toString(); 26 System.out.println(ss); 27 });*/ 28 operatorStr("tom", s -> System.out.println(new StringBuilder(s).reverse().toString())); // mot 29 30 // 方法引用 31 operatorStr("tom", System.out::println); // tom 32 33 System.out.println("================================"); 34 operatorStr( 35 "sam", 36 s -> System.out.println(s), // 效果同System.out::println 37 s -> System.out.println(new StringBuilder(s).reverse().toString()) 38 ); // sam mas 39 } 40 41 // 消费一个字符串数据 42 private static void operatorStr(String name, Consumer<String> con){ 43 con.accept(name); 44 } 45 46 // 用不同方式消费同一个字符串数据两次 47 private static void operatorStr(String name, Consumer<String> con1, Consumer<String> con2){ // 函数重载 48 // con1.accept(name); 49 // con2.accept(name); 50 con1.andThen(con2).accept(name); // 效果同上两行 51 } 52 }
1 package day14.lesson1; 2 3 import java.util.function.Consumer; 4 5 /* 6 1.7 Consumer案例-按要求打印信息 7 8 案例需求 9 String[] strArray = {"林青霞,30", "张曼玉,35", "王祖贤,33"}; 10 字符串数组中有多条信息,请按照格式:“姓名:XX,年龄:XX"的格式将信息打印出来 11 要求: 12 把打印姓名的动作作为第一个Consumer接口的Lambda实例 13 把打印年龄的动作作为第二个Consumer接口的Lambda实例 14 将两个Consumer接口按照顺序组合到一起使用 15 */ 16 public class Demo7Consumer { 17 public static void main(String[] args) { 18 String[] strArr= {"tom,20", "amy,18", "sam,21"}; 19 20 /*printInfo( 21 strArr, 22 (String s) -> { 23 String name = s.split(",")[0]; 24 System.out.print("姓名:" + name); 25 }, 26 (String s) -> { 27 String ageStr = s.split(",")[1]; 28 int age = Integer.parseInt(ageStr); 29 System.out.println(",年龄:" + age); 30 } 31 );*/ 32 33 printInfo( 34 strArr, 35 s -> System.out.print("姓名:" + s.split(",")[0]), 36 s -> System.out.println(",年龄:" + Integer.parseInt(s.split(",")[1])) 37 ); 38 /* 39 姓名:tom,年龄:20 40 姓名:amy,年龄:18 41 姓名:sam,年龄:21 42 */ 43 } 44 45 private static void printInfo(String[] strArr, Consumer<String> con1, Consumer<String> con2){ 46 for (String str: strArr){ 47 /*con1.accept(str); 48 con2.accept(str);*/ 49 con1.andThen(con2).accept(str); 50 } 51 } 52 }