1.Lamdba表达式使得在java编程当中,因为高效的编码方式和对接口与功能实现的分离,极大的减少了编程代码量,下面对四种Lamdba内置接口进行简易的描述和功能介绍。
四种接口:
* Consumer<T> : 消费型接口
* void accept(T t); :有参数,但是没有返回值
*
* Supplier<T> : 供给型接口 :有返回值,但是没有参数
* T get();
*
* Function<T, R> : 函数型接口 :有返回值,也有参数
* R apply(T t);
*
* Predicate<T> : 断言型接口 :返回boolean 类型,有参数
* boolean test(T t);
使用方式:
1.消费型:
//消费型 consumer:特点有一个参数,这个参数进行处理,然后没有返回值
lamdbs.consumerMoney(100, (e)->{System.out.println("我买东西消费了"+e+"元钱");});
//消费型Lamdba使用:
public void consumerMoney(double money,Consumer<Double> cons) {
cons.accept(money);
}
2.供给型:
//供给型,没有参数, 但是能得到一个返回值:如给定一个数,产生一个随机的数组,供给型,没有参数, 但是能得到一个返回值:如给定一个数,产生一个随机的数组
List<Integer> numsBySuppliers = lamdbs.getNumsBySuppliers(10, ()->(int)(Math.random()*100));
public List<Integer> getNumsBySuppliers(int num,Supplier<Integer> sup){
List<Integer> numList=new ArrayList<>();
for(int i=0;i<num;i++) {
Integer intNum = sup.get();
numList.add(intNum);
}
return numList;
}
3.函数型:
int strLengthByFunction = lamdbs.getStrLengthByFunction("wo shi yanghongtang", (e)->e.length());
//函数Lamdba使用--》传进去一个值,然后处理完成后返回一个值,比如:传进去一个字符串,返回该字符串的长度
public int getStrLengthByFunction(String str,Function<String, Integer> fun) {
return fun.apply(str);
}
4.断言型
List<String> filterStr = lamdbs.filterStr(Arrays.asList("alsfowage","aegt","wq4y","wtqt"), (e)->(e.length()>3));
//将满足条件的字符串,放入集合当中
public List<String> filterStr(List<String> list,Predicate<String> pre){
List<String> list1=new ArrayList<>();
for (String string : list) {
if(pre.test(string)) {
list1.add(string);
}
}
return list1;
}