Lamdba表达式
* 相当于提供了一个函数式接口(只拥有一个方法的接口)
* 这个函数式接口可以被调用,实现Lambda的功能
@FunctionalInterface
interface StringFunc {
public String func(String s);
}
public class App13_9 {
static String sop(StringFunc sf, String s) {
return sf.func(s);
}
public static void main(String[] args) {
String outStr,inStr = "Lambda 表达式 good";
System.out.println("原字符串:" + inStr);
outStr = sop((str) -> str.toUpperCase(), inStr);
System.out.println("转换为大写字符后:" + outStr);
outStr = sop((str)->{
String result = "";
for (int i=0; i<str.length(); i++)
if (str.charAt(i) != ' ')
result += str.charAt(i);
return result;
}, inStr);
System.out.println("去掉空格的字符串:" + outStr);
StringFunc reverse = (str)->{
String result="";
for (int i=str.length()-1; i>=0; i--)
result += str.charAt(i);
return result;
};
System.out.println("反序后的字符串:" + sop(reverse, inStr));
}
}
匿名类 -> Lambda表达式 -> 方法引用
案例一:
@FunctionalInterface
interface IShow<P, R> {
public R info(P p);
}
public class App13_10 {
public static void main(String[] args) {
/**
* 匿名类方式
*/
String s = new IShow<Integer, String>() {
@Override
public String info(Integer integer) {
return String.valueOf(integer);
}
}.info(555);
System.out.println("匿名类方式得到的结果:" + s);
/**
* Lambda表达式
* str:代表形参,->后的是info()方法 return后的值
*/
IShow<Integer, String> lam = str-> String.valueOf(str);
String info1 = lam.info(100);
System.out.println(info1);
/**
* 方法引用
*/
IShow<Integer, String> ip = String::valueOf;
String info = ip.info(999);
System.out.println(info);
}
}
案例二
@FunctionalInterface
interface IShow1<T> {
T create(String s, int a);
}
class Person {
String name;
int age;
Person() {
this.name = "刘禅";
this.age = 22;
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
public class App13_11 {
public static void main(String[] args) {
/**
* 匿名类方式
*/
Person person = new IShow1<Person>() {
@Override
public Person create(String s, int a) {
return new Person(s, a);
}
}.create("西瓜", 22);
System.out.println(person);
/**
* Lambda表达式
*/
IShow1<Person> aNew = (name, age) -> {
return new Person(name, age);
};
/**
* 方法引用
*/
aNew = Person::new;
Person person1 = aNew.create("西瓜", 10);
System.out.println(person1.toString());
}
}