当前位置: 首页 > news >正文

Lambda表达式总结

Lambda作为Java8的新特性,本篇文章主要想总结一下常用的一下用法和api

1.接口内默认方法实现

public interface Formula {double calculate(int a);// 默认方法default double sqrt(int a) {return Math.sqrt(a);}
}
public static void main(String[] args) {Formula formula = new Formula() {@Overridepublic double calculate(int a) {return sqrt(a * 100);}};double a1 = formula.calculate(100);double b1 = formula.sqrt(16);System.out.println(a1); // 100.0System.out.println(b1); // 4.0
}

2.lambda表达式

List<String> names = Arrays.asList("peter", "anna", "xenia", "mike");
// 老版本
Collections.sort(names, new Comparator<String>() {@Overridepublic int compare(String o1, String o2) {return o2.compareTo(o1);}
});// lambda写法
Collections.sort(names, (o1, o2) -> o2.compareTo(o1));
// 更简易的写法
names.sort((a,b) ->  b.compareTo(a));
System.out.println(names);

3.函数式接口(Funcation Interface)

java8中:: 关键字引用构造方法,对象方法和静态方法

// 定义: 仅仅包含一个抽象方法的接口, @FunctionalInterface只是一个标识,有没有都可以
// 只有函数式接口才能写成lambda表达式
@FunctionalInterface
public interface Convert<T, R> {R convert(T from);
}// :: 使用关键字来引用类的方法或者构造器
Convert<String, Integer> convert = Integer::valueOf; // 引用静态方法
Integer convert1 = convert.convert("123");
System.out.println(convert1);String s = "hello";
Convert<Integer, String> convert2 = s::substring; // 引用构造方法
String convert3 = convert2.convert(1);
System.out.println(convert3);
Convert<String, String> convert5 = String::new; // 引用构造方法
System.out.println(convert5);
// 定义了一个函数式接口PersonFactory
public interface PersonFactory<P extends Person> {P create(String firstName, String lastName);
}class Person {String firstName;String lastName;Person() {}Person(String firstName, String lastName) {this.firstName = firstName;this.lastName = lastName;}@Overridepublic String toString() {return "Person{" +"firstName='" + firstName + '\'' +", lastName='" + lastName + '\'' +'}';}
}
// 将Person的构造函数作为函数式接口的实现
PersonFactory<Person> personFactory = Person::new;
Person person = personFactory.create("peter", "parker");
System.out.println(person);

4.lambda访问外部变量及接口默认方法

// 定义一个函数式接口
@FunctionalInterface
public interface Convert<T, R> {R convert(T from);
}// 由于Convert是函数式接口,所以可以写成lambda,也就是说可以作为lambda表达式的类型
int num = 1; // num被用在了lambda内,必须为final类型,这里没写是因为是隐式的final类型
Convert<Integer, String> convert4 = (from -> String.valueOf(from + num));
String result = convert4.convert(2);
System.out.println(result);// 访问接口默认方法
@FunctionalInterface
public interface Formula {double calculate(int a);default double sqrt(int a) {return Math.sqrt(a);}
}// 匿名内部类的访问方式
Formula formula = new Formula() {@Overridepublic double calculate(int a) {return sqrt(a * 100);}
};
double a1 = formula.calculate(100);
double b1 = formula.sqrt(16);
System.out.println(a1);
System.out.println(b1);
// Formula formula = (a) -> sqrt(a * 100); 这个可不行,会编译报错

5.内置的函数式接口

5.1 Predicate断言

Predicate<String> isEmpty = String::isEmpty;
System.out.println(isEmpty.test("")); // true
Predicate<String> predicate = (s) -> s.length() > 0;
System.out.println(predicate.test("foo"));              // true
// 返回test()取反的结果
System.out.println(predicate.negate().test("foo"));     // false

5.2 Funcation

Function<String, Integer> function = Integer::valueOf;
// 将两个function组合起来, 先执行function在将function的输出作为输入计算x + 3最终输出结果
Function<String, Integer> function1 = function.andThen(x -> x + 3);
System.out.println(function1.apply("123"));// compose, 从右往左执行
Function<Integer, Integer> addFunction = x -> x + 1;
Function<Integer, Integer> multiplyByTwo = x -> x * 2;
Function<Integer, Integer> square  = x -> x * x;
Function<Integer, Integer> compose = addFunction.compose(multiplyByTwo).compose(square);
Integer apply = compose.apply(1);
System.out.println(apply); // 3

5.3 Supplier 生产者

// 不接收任何参数,直接返回一个指定的结果
Supplier<String> supplier = String::new;
String s1 = supplier.get(); // new String();
// 直接返回一个Person对象
Supplier<Person> supplier1 = Person::new;
Person person1 = supplier1.get();
System.out.println(person1);

5.4 Consumer消费者

// 提供入参 以供消费
Consumer<String> consumer = (p) -> System.out.println(p + " hello world!");
consumer.accept("123"); // 123 hello world!

5.5 Comparator

Comparator<Integer> comparator = (x1, x2) -> x1.compareTo(x2);
int compare = comparator.compare(1, 2);
System.out.println(compare); // 相等返0, 第一个参数 > 第二个参数返回1, 否则返回-1

6 Stream流

List<String> stringCollection = new ArrayList<>();
stringCollection.add("ddd2");
stringCollection.add("aaa2");
stringCollection.add("bbb1");
stringCollection.add("aaa1");
stringCollection.add("bbb3");
stringCollection.add("ccc");
stringCollection.add("bbb2");
stringCollection.add("ddd1");

6.1 Filter过滤

// filter()
stringCollection.stream().filter((s3) -> s3.startsWith("a")).forEach(System.out::println);

6.2 Sorted 排序

// sorted()
stringCollection.stream().sorted().filter((s3) -> s3.startsWith("a")).forEach(System.out::println);

6.3 Map转换

// map()
stringCollection.stream().map(String::toUpperCase).sorted(String::compareTo).forEach(System.out::println);

6.4 Match匹配

// match()
boolean match = stringCollection.stream().anyMatch(s3 -> s3.startsWith("a"));
// 验证stringCollection中是否都不是以a开头
boolean match2 = stringCollection.stream().noneMatch(s3 -> s3.startsWith("a"));
boolean match3 = stringCollection.stream().allMatch(s3 -> s3.startsWith("a"));
System.out.println(match); // true
System.out.println(match2); // false
System.out.println(match3); // false

6.5 Count计数

// count()
long count = stringCollection.stream().filter(s3 -> s3.startsWith("a")).count();
System.out.println(count); // 2

6.6 Reduce

// reduce, 将多个元素归约成一个值
stringCollection.stream().sorted().reduce((s4, s5) -> s4 + "#" + s5).ifPresent(System.out::println);

相关文章:

Lambda表达式总结

Lambda作为Java8的新特性&#xff0c;本篇文章主要想总结一下常用的一下用法和api 1.接口内默认方法实现 public interface Formula {double calculate(int a);// 默认方法default double sqrt(int a) {return Math.sqrt(a);} }public static void main(String[] args) {Form…...

岛屿的最大面积

给你一个大小为 m x n 的二进制矩阵 grid 。 岛屿 是由一些相邻的 1 (代表土地) 构成的组合&#xff0c;这里的「相邻」要求两个 1 必须在 水平或者竖直的四个方向上 相邻。你可以假设 grid 的四个边缘都被 0&#xff08;代表水&#xff09;包围着。 岛屿的面积是岛上值为 1 …...

迭代器模式(Iterator)

迭代器模式是一种行为设计模式&#xff0c;可以在不暴露底层实现(列表、栈或树等)的情况下&#xff0c;遍历一个聚合对象中所有的元素。 Iterator is a behavior design pattern that can traverse all elements of an aggregate object without exposing the internal imple…...

Goland搭建远程Linux开发

Windows和Linux都需要先构建好go环境&#xff0c;启用ssh服务。 打开Windows上的Goland&#xff0c;建立项目。 点击添加配置&#xff0c;选择go构建 点击运行于&#xff0c;选择ssh 填上Linux机器的IP地址和用户名 输入密码 没有问题 为了不让每次运行程序和调试程序都生…...

react中PureComponent的理解与使用

一、作用 它是一个纯组件&#xff0c;会做一个数据的浅比较&#xff0c;当props和state没改变的时候&#xff0c;不会render重新渲染&#xff0c; 改变后才会render重新渲染&#xff0c;提高性能。 二、使用 三、注意 它不能和shouldComponentUpdate生命周期同时使用。因为它…...

洛谷——P5714 【深基3.例7】肥胖问题

文章目录 题目题目描述输入格式输出格式样例 #1样例输入 #1样例输出 #1 样例 #2样例输入 #2样例输出 #2 提示 AC代码 题目 题目描述 BMI 指数是国际上常用的衡量人体胖瘦程度的一个标准&#xff0c;其算法是 m h 2 \dfrac{m}{h^2} h2m​&#xff0c;其中 m m m 是指体重&am…...

Mac隐藏和显示文件

由于之前没有使用过Mac本&#xff0c;所以很多地方都不太清楚&#xff0c;在下载git项目的时候&#xff0c;发现没有.git文件&#xff0c; 一开始还以为下载错了&#xff0c;但是git命令是可以看到远端分支以及当前分支的&#xff0c;之后在一次解压文件的时候发现&#xff0c;…...

软件工程中应用的几种图辨析

【软件工程】软件工程中应用的几种图辨析&#xff1a;系统流程图、数据流图、数据字典、实体联系图、状态转换图、层次方框图、Warnier图、IPO图、层次图、HIPO图、结构图、程序流程图、盒图、PAD图、判定表_眩晕李的博客-CSDN博客 软件工程——实体关系图 状态转换图 数据流…...

下载离线版的VS Visual Studio 并下载指定的版本

一、先下载引导程序 下载地址VS VisualStudio官网 在这个页面翻到最下面 在这里下载需要的版本 下载引导程序 二、下载离线安装包 写一个批处理文件&#xff08;vs.bat&#xff09; 命令格式如下 <vs引导程序exe> --layout <离线安装包下载的路径> --add <功能…...

Eureka 学习笔记5:InstanceRegistry

版本 awsVersion ‘1.11.277’ LeaseManager 接口管理实例的租约信息&#xff0c;提供以下功能&#xff1a; 注册实例取消注册实例实例续约剔除过期实例 public interface LeaseManager<T> {/** 注册实例并续约*/void register(T r, int leaseDuration, boolean isRep…...

System Verilog——虚方法的使用

1、使用虚方法目的 通过在父类里定义虚方法(task or function)&#xff0c;可以在当父类句柄调用一个方法时候&#xff0c;前提是若是这个句柄指向了子类对象&#xff0c;则调用的方法为子类的方法而不是父类的方法。 1.1、实例理解&#xff1a;将子类句柄赋值成父类句柄 mod…...

线性规划和单纯形法-原理篇

文章目录 引言线性规划标准型问题特点单纯形法 引言 很多运筹学的教材都是从线性规划开始的&#xff0c;我平时做算法策略的落地应用时也研发了一部分基于线性规划的技术方案。可以说&#xff0c;如果搞不懂线性规划&#xff0c;很难成为一名优秀的运筹优化算法工程师。 但是…...

FBX SDK开发快速上手指南

一段时间以来&#xff0c;我一直想制作一个 FBX Exporter 将 FBX 文件转换为我自己的格式。 整个过程不是很顺利&#xff0c;主要是FBX的官方文档不是很清楚。 另外&#xff0c;由于 FBX 格式被许多应用程序使用&#xff0c;而不仅仅是游戏引擎&#xff0c;因此提供的示例代码没…...

探讨|使用或不使用机器学习

动动发财的小手&#xff0c;点个赞吧&#xff01; 机器学习擅长解决某些复杂问题&#xff0c;通常涉及特征和结果之间的困难关系&#xff0c;这些关系不能轻易地硬编码为启发式或 if-else 语句。然而&#xff0c;在决定 ML 是否是当前给定问题的良好解决方案时&#xff0c;有一…...

Git笔记--Ubuntu上传本地项目到github

目录 1--基本配置 2--本地上传 1--基本配置 ① 创建ssh-key cd ~/.sshssh-keygen -t rsa -C "邮箱地址"② 查看并关联ssh-key gedit id_rsa.pub 复制内容&#xff0c;在 GitHub 中依次点击 Settings -> SSH and GPG keys -> New SSH key&#xff0c;将 id…...

基于Go编写一个可视化Navicat本地密码解析器

前提 开发小组在测试环境基于docker构建和迁移一个MySQL8.x实例&#xff0c;过程中大意没有记录对应的用户密码&#xff0c;然后发现某开发同事本地Navicat记录了根用户&#xff0c;于是搜索是否能够反解析Navicat中的密码掩码&#xff08;这里可以基本断定Navicat对密码是采用…...

Maven【入门笔记】

Maven 解决版本依赖的问题 https://www.liaoxuefeng.com/wiki/1252599548343744/1309301146648610 如果没有项目管理工具&#xff0c;在开发项目的时候&#xff0c;我们需要手动管理依赖包&#xff0c;需要管理依赖包的版本、去找到并下载依赖包、还有依赖包所依赖的包 等等。…...

Android Studio中使用cmake开发JNI实战

JNI学习大纲 一、JNI编程入门 二、Android Studio中使用cmake开发JNI实战 第一章节我们介绍了JNI的开发步骤&#xff0c;那这一章节我们就开始在Android Studio中实战一下吧&#xff0c;Lets Start。 1. Android Studio中安装CMake插件 AS中菜单栏选择Tools>SDK Manager在…...

第七章 图论

第七章 图论 一、数据结构定义 图的邻接矩阵存储法#define MaxVertexNum 100 // 节点数目的最大值// 无边权&#xff0c;只用0或1表示边是否存在 bool graph[MaxVertexNum][MaxVertexNum];// 有边权 int graph[MaxVertexNum][MaxVertexNum];图的邻接表存储法 把所有节点存储为…...

IEEE SystemVerilog Chapter13 : Tasks and functions (subroutines)

13.2 Overview 任务和函数提供了从描述中的几个不同位置执行通用过程的能力。它们还提供了一种将大型过程分解为小型过程的方法&#xff0c;以便更容易地阅读和调试源代码描述。本小节讨论了任务和函数之间的区别&#xff0c;描述了如何定义和调用任务和函数&#xff0c;并给出…...

Linux应用开发之网络套接字编程(实例篇)

服务端与客户端单连接 服务端代码 #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <arpa/inet.h> #include <pthread.h> …...

在软件开发中正确使用MySQL日期时间类型的深度解析

在日常软件开发场景中&#xff0c;时间信息的存储是底层且核心的需求。从金融交易的精确记账时间、用户操作的行为日志&#xff0c;到供应链系统的物流节点时间戳&#xff0c;时间数据的准确性直接决定业务逻辑的可靠性。MySQL作为主流关系型数据库&#xff0c;其日期时间类型的…...

19c补丁后oracle属主变化,导致不能识别磁盘组

补丁后服务器重启&#xff0c;数据库再次无法启动 ORA01017: invalid username/password; logon denied Oracle 19c 在打上 19.23 或以上补丁版本后&#xff0c;存在与用户组权限相关的问题。具体表现为&#xff0c;Oracle 实例的运行用户&#xff08;oracle&#xff09;和集…...

Unity3D中Gfx.WaitForPresent优化方案

前言 在Unity中&#xff0c;Gfx.WaitForPresent占用CPU过高通常表示主线程在等待GPU完成渲染&#xff08;即CPU被阻塞&#xff09;&#xff0c;这表明存在GPU瓶颈或垂直同步/帧率设置问题。以下是系统的优化方案&#xff1a; 对惹&#xff0c;这里有一个游戏开发交流小组&…...

centos 7 部署awstats 网站访问检测

一、基础环境准备&#xff08;两种安装方式都要做&#xff09; bash # 安装必要依赖 yum install -y httpd perl mod_perl perl-Time-HiRes perl-DateTime systemctl enable httpd # 设置 Apache 开机自启 systemctl start httpd # 启动 Apache二、安装 AWStats&#xff0…...

关于nvm与node.js

1 安装nvm 安装过程中手动修改 nvm的安装路径&#xff0c; 以及修改 通过nvm安装node后正在使用的node的存放目录【这句话可能难以理解&#xff0c;但接着往下看你就了然了】 2 修改nvm中settings.txt文件配置 nvm安装成功后&#xff0c;通常在该文件中会出现以下配置&…...

python如何将word的doc另存为docx

将 DOCX 文件另存为 DOCX 格式&#xff08;Python 实现&#xff09; 在 Python 中&#xff0c;你可以使用 python-docx 库来操作 Word 文档。不过需要注意的是&#xff0c;.doc 是旧的 Word 格式&#xff0c;而 .docx 是新的基于 XML 的格式。python-docx 只能处理 .docx 格式…...

如何理解 IP 数据报中的 TTL?

目录 前言理解 前言 面试灵魂一问&#xff1a;说说对 IP 数据报中 TTL 的理解&#xff1f;我们都知道&#xff0c;IP 数据报由首部和数据两部分组成&#xff0c;首部又分为两部分&#xff1a;固定部分和可变部分&#xff0c;共占 20 字节&#xff0c;而即将讨论的 TTL 就位于首…...

视觉slam十四讲实践部分记录——ch2、ch3

ch2 一、使用g++编译.cpp为可执行文件并运行(P30) g++ helloSLAM.cpp ./a.out运行 二、使用cmake编译 mkdir build cd build cmake .. makeCMakeCache.txt 文件仍然指向旧的目录。这表明在源代码目录中可能还存在旧的 CMakeCache.txt 文件,或者在构建过程中仍然引用了旧的路…...

【从零学习JVM|第三篇】类的生命周期(高频面试题)

前言&#xff1a; 在Java编程中&#xff0c;类的生命周期是指类从被加载到内存中开始&#xff0c;到被卸载出内存为止的整个过程。了解类的生命周期对于理解Java程序的运行机制以及性能优化非常重要。本文会深入探寻类的生命周期&#xff0c;让读者对此有深刻印象。 目录 ​…...