文章目录
Lambda表达式
Lambda表达式代码示例
public class Demo09_Lambda表达式2 {
public static void main(String[] args) {
Inter2 i1 = new Inter2() {
@Override
public void test(String x) {
System.out.println(x);
}
};
i1.test("Hello Noname innerclass");
Inter2 i2 = qq -> System.out.println(qq);
i2.test("Hello Lambda");
}
}
interface Inter2 {
public abstract void test(String x);
}
函数式接口
常用函数式接口
消费型函数式接口
消费型函数式接口代码示范
import java.util.function.Consumer;
public class Demo12_函数式接口_消费性接口 {
public static void main(String[] args) {
happy(8000, x -> System.out.println("班长喜欢大宝剑,每次消费" + x + "元"));
}
public static void happy(int money, Consumer<Integer> con) {
con.accept(money);
}
}
供给型函数式接口
供给型函数式接口代码示范
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.function.Supplier;
public class Demo13_函数式接口_供给型接口 {
public static void main(String[] args) {
// List<Integer> list = getNumList(10, () -> {
// Random rd = new Random();
// int x = rd.nextInt(31) + 20;
// return x;
//
// });
List<Integer> list = getNumList(10, () -> new Random().nextInt(31) + 20);
System.out.println(list);
}
public static List<Integer> getNumList(int num, Supplier<Integer> sup) {
List<Integer> list = new ArrayList<>();
for(int i = 1; i <= num; i++) {
list.add(sup.get());
}
return list;
}
}
函数型函数式接口
函数型函数式接口代码示范
import java.util.function.Function;
public class Demo14_函数式接口_函数型接口 {
public static void main(String[] args) {
//调用strHandler方法,将字符串两端的空格删除
String result = strHandler("\t\t\t我丢雷楼某 ! ", x -> x.trim());
System.out.println(result);
}
public static String strHandler(String str, Function<String, String> fun) {
return fun.apply(str);
}
}