函数式接口实例之Function、Consumer、Predicate"/>
常用的函数式接口实例之Function、Consumer、Predicate
函数式接口,即有且仅有一个抽象方法的接口,我用一个小demo来定义一个简单的函数式接口;
先创建一个接口,并且添加@FunctionalInterface注解,通知编译器这是函数式接口,进行抽象方法检查;
@FunctionalInterface
public interface MathOperation {public Float operate(Integer a ,Integer b);
}
函数式编程是以Lambda表达式所体现的,在main方法中,使用Lambda表达式实现;接下来另起一类,在mian方法中编写输出;
加法操作 - Lambda表达式
MathOperation addition = (Integer a,Integer b)->{return a+b+0f;};System.out.println(addition.operate(5,3));
加法操作 - 实现接口
class Addition implements MathOperation{@Overridepublic Float operate(Integer a, Integer b) {return a+b+0f;}}Addition addition = new Addition();System.out.println(addition.operate(5,3));
减法操作 - Lambda忽略参数类型写法
MathOperation substraction = (a,b)->{return a-b+0f;};System.out.println(substraction.operate(5,3));
乘法操作 - 单行实现代码省略大括号和return
MathOperation multiplication = (a,b)->a*b+0f;System.out.println(multiplication.operate(5,3));
看完这个demo,应该明白了lambda表达式基本写法,以及函数式接口的定义;接下是Function、Consumer、Predicate三个常用函数式接口的使用;
1.Function - apply
Function:表示接收一个参数并产生结果的函数
R r = apply(T t):转换过的数据进行传递,接受一个T类型的参数,并返回一个String类型的返回值
生成定长的随机字符
public class FunctionSample {public static void main(String[] args) {Function<Integer, String> randomStringFunction = l -> {String chars = "abcdefghijklmnopqrstuvxwyz46378468324";StringBuffer stringBuffer = new StringBuffer();Random random = new Random();for (int i = 0; i < l; i++) {// 生成0~length之间的任意整数int position = random.nextInt(chars.length());// 末端添加stringBuffer.append(chars.charAt(position));}return stringBuffer.toString();};String randomString = randomStringFunction.apply(32);System.out.println(randomString);}
}
2.Consumer - accept
Consumer:表示接受单个输入参数并且不返回结果的操作
voide accept(T t):对给定的参数执行此操作
向控制台输出
public class ConsumerSample {public static void main(String[] args) {output(s-> System.out.println("输出1:" + s));output(s->{System.out.println("输出2:" + s);});}public static void output(Consumer<String> consumer){String text = "我是一个小demo";consumer.accept(text);}
}
3.Predicate - test
boolean b = test(T t):在给定的参数t上,判断这个参数t
判断对错以及过滤数组的数
public class PredicateSample {public static void main(String[] args) {Predicate<Integer> predicate = n->n<4;boolean result = predicate.test(10);System.out.println(result);List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);filter(list,n->n%2==1); //取所有奇数filter(list,n->n%2==0); //取所有偶数filter(list,n->n>3 && n%2==0); //取所有大于3的偶数}public static void filter(List<Integer> list , Predicate<Integer> predicate){for(Integer num:list){if(predicate.test(num)){System.out.print(num + " ");}}System.out.println("");}
}
更多推荐
常用的函数式接口实例之Function、Consumer、Predicate
发布评论