常用函数式Consumer接口练习
1 package LambdaTest.LambdaTest04; 2 3 import java.util.function.Consumer; 4 5 /** 6 * FileName: ConsumerTest 7 * Author: lps 8 * Date: 2022/4/5 17:21 9 * Sign:刘品水 Q:1944900433 10 * 11 * @FunctionalInterface public interface Consumer<T> 12 * 表示接受一个输入参数,并返回没有结果的操作。不像大多数其他的功能接口, Consumer有望通过的副作用。 13 * 这是一个functional interface其功能的方法是accept(Object)。 14 * <p> 15 * void accept(T t) 16 * 在给定的参数上执行此操作。 17 * default Consumer<T> andThen(Consumer<? super T> after) 18 * 返回一个由 Consumer执行此操作,在序列,其次是 after操作。 19 */ 20 public class ConsumerTest { 21 public static void main(String[] args) { 22 operatorString("刘品水", s -> System.out.println(s)); 23 //operatorString("刘品水",System.out::println); 24 25 //StringBuilder reverse() 26 //使这个字符序列被序列的反转所取代。 27 operatorString("刘品水", s -> { 28 String sb = new StringBuilder(s).reverse().toString(); 29 System.out.println(sb); 30 }); 31 System.out.println("==========="); 32 operatorString("刘品水", lps -> System.out.println(lps), 33 lps -> System.out.println(new StringBuilder(lps).reverse().toString())); 34 35 36 37 } 38 39 private static void operatorString(String name, Consumer<String> con1, Consumer<String> con2) { 40 // con1.accept(name); 41 // con2.accept(name); 42 //default Consumer<T> andThen(Consumer<? super T> after) 43 //返回一个由 Consumer执行此操作,在序列,其次是 after操作。 44 con1.andThen(con2).accept(name); 45 } 46 47 private static void operatorString(String name, Consumer<String> con) { 48 con.accept(name); 49 } 50 51 52 }
package LambdaTest.LambdaTest05; import java.util.function.Consumer; /** * FileName: ConsumerTest * Author: lps * Date: 2022/4/5 19:51 * Sign:刘品水 Q:1944900433 */ public class ConsumerTest { public static void main(String[] args) { String[] strsArray = {"刘品水,20", "彭于晏,28", "吴彦祖,26"}; // PrintInfo(strsArray, (String str) -> { // String name = str.split(",")[0]; // System.out.print("姓名:" + name); // // }, (String str) -> { // int age = Integer.parseInt(str.split(",")[1]); // System.out.println(",年龄为:" + age); // } // ); PrintInfo(strsArray,str-> System.out.print("姓名:"+str.split(",")[0]), str0-> System.out.println(",年龄:"+Integer.parseInt(str0.split(",")[1]))); } private static void PrintInfo(String[] strArray, Consumer<String> con1, Consumer<String> con2) { for (String s : strArray) { con1.andThen(con2).accept(s); } } }