Lambda表达式的标准格式为:
(参数类型1 参数名称1,参数类型2 参数名称2,…) ‐> { 代码语句 }
省略规则
在Lambda标准格式的基础上,使用省略写法的规则为:
- 小括号内参数的类型可以省略;
- 如果小括号内有且仅有一个参,则小括号可以省略;
- 如果大括号内有且仅有一个语句,则无论是否有返回值,都可以省略大括号、return关键字及语句分号。
Lambda使用前提
1、必须是函数式接口,例如Runnable 、 Comparator等
2、使用Lambda必须具有上下文推断。即方法的参数或局部变量类型必须为Lambda对应的接口类型,才能使用Lambda作为该接口的实例
常见的函数式接口
1.Consumer T:消费型接口
方法:void accept(T t)
2.Supplier T(<>):生产型接口
方法:T get()
public class Test02 {
public static void main(String[] args) {
/**
*随机获取一个45~88的整数
*/
f(()->new Random().nextInt(88-45+1)+45);
}
//生产型函数式接口
public static void f(Supplier<Integer> sup){
System.out.println(sup.get());
}
}
3.Predicate T 判断
方法:boolean test(T t)
public class TestRegexAndFuncInterface {
public static void main(String[] args) {
/**
*用正则表达式判断一个字符是否是一个邮箱
* 格式:前两位是小写字母,然后是4-6位数字,然后是@,
* 之后是由2~4位数字或者小写字符,最后.com结尾
*/
String rege = "^[a-z]{2}\\d{4,6}@[0-9|a-z]{2}\\.com$";
//方法一:函数式接口,lambda表达式
f(s->s.matches(rege),"ew45236@35.com");
//方法二:传统方法
boolean g = g(rege,"ew45236@35.com");
System.out.println(g);
System.out.println("===========================");
/**
* 判断是否是手机号:第一位是1,第二位是3-9,11位数字
*/
String rege2 = "^1[3-9][0-9]{9}$";
f(s -> s.matches(rege2),"1309876543");
}
public static void f(Predicate<String> pre,String s){
System.out.println(pre.test(s));
}
public static boolean g(String r,String s){
return s.matches(r);
}
}
4.Function<T,R> 函数型函数式接口
方法:R apply(T t)
public class Test01 {
public static void main(String[] args) {
/**
* 统计字符串中的每一个字符
*/
Scanner sc = new Scanner(System.in);
String s = sc.next();
//方法一:消费式函数接口
/*g(s1->{
Map<String,Integer> map = new HashMap<>();
for (int i = 0; i < s1.length(); i++) {
String c = String.valueOf(s1.charAt(i));
if (map.containsKey(c)){
Integer count = map.get(c);
count++;
map.put(c,count);
}else{
map.put(c,1);
}
}
Set<String> keys = map.keySet();
for (String key : keys) {
Integer value = map.get(key);
System.out.println(key+":"+value);
}
},s);*/
//方法二:函数型函数式接口
f1(s1->{
HashMap<String,Integer> map = new HashMap<>();
for (int i = 0; i < s1.length(); i++) {
String c = String.valueOf(s1.charAt(i));
if (map.containsKey(c)){
Integer count = map.get(c);
count++;
map.put(c,count);
}else{
map.put(c,1);
}
}
return map;
},s);
}
//方法一:消费式函数接口
public static void g(Consumer<String> con,String s){
con.accept(s);
}
//方法二:函数型函数式接口
public static void f1(Function<String,HashMap<String,Integer>> fun,String s){
System.out.println(fun.apply(s));
}
}