JDK8新特性02 Lambda表达式02_Lambda语法规则
- //函数式接口:只有一个抽象方法的接口称为函数式接口。 可以使用注解 @FunctionalInterface 修饰
- @FunctionalInterface
- public interface MyFun {
- public Integer getValue(Integer num);
- }
- import java.util.ArrayList;
- import java.util.Comparator;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import java.util.function.Consumer;
- import org.junit.Test;
- /*
- * 一、Lambda 表达式的基础语法:Java8中引入了一个新的操作符 "->" 该操作符称为箭头操作符或 Lambda 操作符
- * 箭头操作符将 Lambda 表达式拆分成两部分:
- *
- * 左侧:Lambda 表达式的参数列表
- * 右侧:Lambda 表达式中所需执行的功能, 即 Lambda 体
- *
- * 语法格式一:无参数,无返回值
- * () -> System.out.println("Hello Lambda!");
- *
- * 语法格式二:有一个参数,并且无返回值
- * (x) -> System.out.println(x)
- *
- * 语法格式三:若只有一个参数,小括号可以省略不写
- * x -> System.out.println(x)
- *
- * 语法格式四:有两个以上的参数,有返回值,并且 Lambda 体中有多条语句
- * Comparator<Integer> com = (x, y) -> {
- * System.out.println("函数式接口");
- * return Integer.compare(x, y);
- * };
- *
- * 语法格式五:若 Lambda 体中只有一条语句, return 和 大括号都可以省略不写
- * Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
- *
- * 语法格式六:Lambda 表达式的参数列表的数据类型可以省略不写,因为JVM编译器通过上下文推断出,数据类型,即“类型推断”
- * (Integer x, Integer y) -> Integer.compare(x, y);
- *
- * 上联:左右遇一括号省
- * 下联:左侧推断类型省
- * 横批:能省则省
- *
- * 二、Lambda 表达式需要“函数式接口”的支持
- * 函数式接口:接口中只有一个抽象方法的接口,称为函数式接口。 可以使用注解 @FunctionalInterface 修饰
- * 可以检查是否是函数式接口
- */
- public class TestLambda2 {
- @Test
- public void test1(){
- int num = 0;//jdk 1.7 前,必须是 final
- Runnable r = new Runnable() {
- @Override
- public void run() {
- System.out.println("Hello World!" + num);
- }
- };
- r.run();
- System.out.println("-------------------------------");
- Runnable r1 = () -> System.out.println("Hello Lambda!");
- r1.run();
- }
- @Test
- public void test2(){
- Consumer<String> con = x -> System.out.println(x);
- con.accept("我大尚硅谷威武!");
- }
- @Test
- public void test3(){
- Comparator<Integer> com = (x, y) -> {
- System.out.println("函数式接口");
- return Integer.compare(x, y);
- };
- }
- @Test
- public void test4(){
- Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
- }
- /**自动推断类型*/
- @Test
- public void test5(){
String[] aaa = {"abc","def","ghi"}; //后面的值也没有写类型,根据前面自动推断出来的- // String[] strs;
- // strs = {"aaa", "bbb", "ccc"}; 拆开写无法推断出类型,会报错
- List<String> list = new ArrayList<>(); //java7 后面不用写类型了,因为可以根据前面推断出来,只写一个<> 即可
- show(new HashMap<>()); //在Java8中,show()方法中创建的Map用泛型即可,因为可以根据方法类型自动推断出
- }
- public void show(Map<String, Integer> map){ //方法定义中已经指定了类型
- }
- //需求:对一个数进行运算
- @Test
- public void test6(){
- Integer num = operation(100, (x) -> x * x);
- System.out.println(num);
- System.out.println(operation(200, (y) -> y + 200));
- }
- public Integer operation(Integer num, MyFun mf){
- return mf.getValue(num);
- }
- }
小例子:
- public class Test {
- /**
- * 1.调用Collection.sort()方法,通过定制排序比较2个Employee(先按年龄比,年龄一样按姓名比),使用lambda表达式传递参数
- */
- public static void main(String[] args) {
- List<Employee> emps = Arrays.asList(
- new Employee(101, "张三", 18, 9999.99),
- new Employee(102, "李四", 59, 6666.66),
- new Employee(103, "王五", 28, 3333.33),
- new Employee(104, "赵六", 8, 7777.77),
- new Employee(105, "田七", 38, 5555.55)
- );
- Collections.sort(emps,(x1,x2) -> {
- if(x1.getAge() == x2.getAge())
- return x1.getName().compareTo(x2.getName());
- else
- return -Integer.compare(x1.getAge(),x2.getAge());
- });
- for (Employee emp : emps)
- System.out.println(emp);
- }
- }
- /**
- * 1.声明函数式接口,接口中声明抽象方法,public String getValue(String str);
- * 2.声明测试类,类中编写方法使用接口作为参数,
- * 1)讲一个字符串转换为大写
- * 2)去掉首位空格
- * 3)截取字符串
- */
- @FunctionalInterface
- public interface MyFunction {
- public String getValue(String str);
- }
- public class Test {
- public static void main(String[] args) {
- System.out.println(handleStr("hello world", x -> x.toUpperCase()));
- System.out.println(handleStr("\t\t\t hello world", x -> x.trim()));
- System.out.println(handleStr("hello world", x -> x.substring(0,2)));
- }
- public static String handleStr(String str, MyFunction mf) {
- return mf.getValue(str);
- }
- }
- /**
- * 1.声明一个带2个泛型的函数式接口,泛型类型为<T,R> T为参数,R为返回值
- * 2.接口中声明对应抽象方法
- * 3.在测试类中声明方法,使用接口做为参数,计算2个Long类型参数的和
- * 4.再计算2个Long类型参数的乘积
- */
- @FunctionalInterface
- public interface MyFunction2<T,R> {
- R getValue(T t1, T t2);
- }
- public class Test {
- public static void main(String[] args) {
- System.out.println(handleLong(100L,200L,(l1,l2) -> l1 + l2));
- System.out.println(handleLong(100L,200L,(l1,l2) -> l1 * l2));
- }
- public static Long handleLong(Long l1,Long l2, MyFunction2<Long,Long> mf) {
- return mf.getValue(l1,l2);
- }
JDK8新特性02 Lambda表达式02_Lambda语法规则的更多相关文章
- 【Java8新特性】Lambda表达式基础语法,都在这儿了!!
写在前面 前面积极响应读者的需求,写了两篇Java新特性的文章.有小伙伴留言说:感觉Lambda表达式很强大啊!一行代码就能够搞定那么多功能!我想学习下Lambda表达式的语法,可以吗?我的回答是:没 ...
- JDK8新特性:Lambda表达式
Lambda表达式,案例一:new Thread(() -> System.out.println("thread")); Lambda表达式,案例二:由参数/箭头和主体组成 ...
- JDK8新特性(一) Lambda表达式及相关特性
函数式接口 函数式接口是1.8中的新特性,他不属于新语法,更像是一种规范 面向对象接口复习 在这里先回顾一下面向对象的接口,创建接口的关键字为interface,这里创建一个日志接口: public ...
- JDK8新特性之Lambda表达式
Lambda表达式主要是替换了原有匿名内部类的写法,也就是简化了匿名内部类的写法.lambda语法结构: (参数1,参数2...)->{重写方法的内容,不定义方法名} 先看一个使用匿名内部类定义 ...
- JDK8新特性01 Lambda表达式01_设计的由来
1.java bean public class Employee { private int id; private String name; private int age; private do ...
- jdk8新特性--使用lambda表达式的延迟执行特性优化性能
使用lambda表达式的延迟加载特性对代码进行优化:
- JDK8新特性03 Lambda表达式03_Java8 内置的四大核心函数式接口
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.functio ...
- java8新特性: lambda表达式:直接获得某个list/array/对象里面的字段集合
java8新特性: lambda表达式:直接获得某个list/array/对象里面的字段集合 比如,我有一张表: entity Category.java service CategoryServic ...
- Java8 新特性学习 Lambda表达式 和 Stream 用法案例
Java8 新特性学习 Lambda表达式 和 Stream 用法案例 学习参考文章: https://www.cnblogs.com/coprince/p/8692972.html 1.使用lamb ...
随机推荐
- CSS垂直翻转与水平翻转
/*水平翻转*/ .flipx { -moz-transform:scaleX(-1); -webkit-transform:scaleX(-1); -o-transform:scaleX(-1); ...
- hdu 1686 Oulipo (kmp)
Problem Description The French author Georges Perec (1936–1982) once wrote a book, La disparition, w ...
- 网页发起qq临时会话
qq官方:http://shang.qq.com/v3/widget.html
- 纪中2018暑假培训day1提高b组改题记录
收到意见,认为每天的程序和随笔放在一起写的博客太长了,于是分开整理 day1 模拟赛,看了看提高a组t1的样例就不太想写,于是转而写b组 t1: Description 给定一个n个点m条边的有向图, ...
- PHP中empty,is_null,isset的区别
有时候分不清这几个的区别,特此记录,以备不时之需 isset 判断变量是否已存在 empty 判断变量是否为空或为0 is_null 判断变量是否为NULL 变量 empty is_null isse ...
- JQERY EasyUI Tabs 选项卡 自适应浏览器宽度高度 解决方案
<script type="text/javascript"> $(window).resize(function () { $('#tt').tabs({ width ...
- php项目核心业务(增、删、改、查)(第三篇)
对增删改查数据库的封装 //php对数据库的封装 //Mysql_fetach($sql)函数查询所有的 function Mysql_fetach($sql){ $conn=mysqli_conne ...
- 字符输入流 FileReader
package cn.lideng.demo3; import java.io.FileNotFoundException; import java.io.FileReader; public cla ...
- Linux 普通用户免密码切换到root用户
Linux 普通用户免密码切换到root用户 # 添加用户 useradd user_name # 修改密码 echo "user_name@pwd" | passwd --std ...
- bzoj1009 KMP+矩阵dp
https://www.lydsy.com/JudgeOnline/problem.php?id=1009 阿申准备报名参加GT考试,准考证号为N位数X1X2....Xn(<=Xi<=), ...