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

Lambda-常见的函数式接口

如果需要使用Lambda接口,就必须要有一个函数式接口

函数式接口是有且仅有一个抽象方法的接口, 对应的注解是@FunctionalInterface

Java中内置的常见函数式接口如下:

1.Runnable/ Callable

/*** The <code>Runnable</code> interface should be implemented by any* class whose instances are intended to be executed by a thread. The* class must define a method of no arguments called <code>run</code>.* <p>* This interface is designed to provide a common protocol for objects that* wish to execute code while they are active. For example,* <code>Runnable</code> is implemented by class <code>Thread</code>.* Being active simply means that a thread has been started and has not* yet been stopped.* <p>* In addition, <code>Runnable</code> provides the means for a class to be* active while not subclassing <code>Thread</code>. A class that implements* <code>Runnable</code> can run without subclassing <code>Thread</code>* by instantiating a <code>Thread</code> instance and passing itself in* as the target.  In most cases, the <code>Runnable</code> interface should* be used if you are only planning to override the <code>run()</code>* method and no other <code>Thread</code> methods.* This is important because classes should not be subclassed* unless the programmer intends on modifying or enhancing the fundamental* behavior of the class.** @author  Arthur van Hoff* @see     java.lang.Thread* @see     java.util.concurrent.Callable* @since   JDK1.0*/
@FunctionalInterface
public interface Runnable {/*** When an object implementing interface <code>Runnable</code> is used* to create a thread, starting the thread causes the object's* <code>run</code> method to be called in that separately executing* thread.* <p>* The general contract of the method <code>run</code> is that it may* take any action whatsoever.** @see     java.lang.Thread#run()*/public abstract void run();
}

分别用匿名内部类和Lambda实现Runnable

public class RunnableLambda {public static void main(String[] args) {new Thread(new Runnable() {@Overridepublic void run() {String name = Thread.currentThread().getName();System.out.println(name);}}).start();new Thread(()->{String name = Thread.currentThread().getName();System.out.println(name);}).start();}
}

Callable和Runnable类似

2.Supplier

特点:无方法参数, 返回值为定义的泛型

JDK中Supplier对应的定义:

package java.util.function;/*** Represents a supplier of results.** <p>There is no requirement that a new or distinct result be returned each* time the supplier is invoked.** <p>This is a <a href="package-summary.html">functional interface</a>* whose functional method is {@link #get()}.** @param <T> the type of results supplied by this supplier** @since 1.8*/
@FunctionalInterface
public interface Supplier<T> {/*** Gets a result.** @return a result*/T get();
}

Supplier的使用

public class SupplierLambda {public static void main(String[] args) {int[] arr = {2, 5, 8, 10, 500, 500, 50000};int max = getMax(() -> {int curMax = arr[0];for(int i = 1; i < arr.length; i++) {if(arr[i] > curMax) {curMax = arr[i];}}return curMax;});System.out.println(max);}public static int getMax(Supplier<Integer> supplier) {return supplier.get();}
}

3.Consumer

特点:一个输入参数 无输出 可以对一个入参进行多次使用(使用andThen)

JDK中Consumer的定义

package java.util.function;import java.util.Objects;/*** Represents an operation that accepts a single input argument and returns no* result. Unlike most other functional interfaces, {@code Consumer} is expected* to operate via side-effects.** <p>This is a <a href="package-summary.html">functional interface</a>* whose functional method is {@link #accept(Object)}.** @param <T> the type of the input to the operation** @since 1.8*/
@FunctionalInterface
public interface Consumer<T> {/*** Performs this operation on the given argument.** @param t the input argument*/void accept(T t);/*** Returns a composed {@code Consumer} that performs, in sequence, this* operation followed by the {@code after} operation. If performing either* operation throws an exception, it is relayed to the caller of the* composed operation.  If performing this operation throws an exception,* the {@code after} operation will not be performed.** @param after the operation to perform after this operation* @return a composed {@code Consumer} that performs in sequence this* operation followed by the {@code after} operation* @throws NullPointerException if {@code after} is null*/default Consumer<T> andThen(Consumer<? super T> after) {Objects.requireNonNull(after);return (T t) -> { accept(t); after.accept(t); };}
}

Consumer的使用

import java.util.function.Consumer;public class ConsumerLambda {public static void main(String[] args) {consumerString(s-> System.out.println(s.toUpperCase()),s-> System.out.println(s.toLowerCase()));}static void consumerString(Consumer<String> comsumer) {comsumer.accept("Hello");}static void consumerString(Consumer<String> firstConsumer, Consumer<String> secondConsumer) {firstConsumer.andThen(secondConsumer).accept("Hello");}
}

4.Comparator

特点:两个参数(类型根据指定的泛型),返回值为int

JDK中关于Comparator的定义太长有500多行,我这里就不贴了,自己去看吧

使用如下:

import java.util.Arrays;
import java.util.Comparator;public class ComparatorLambda {public static void main(String[] args) {String[] strs = {"delay","a", "ab", "abc", "bcd"};Comparator<String> comparator = new Comparator<String>() {@Overridepublic int compare(String o1, String o2) {return o1.length() - o2.length();}};Arrays.sort(strs, comparator);System.out.println(Arrays.toString(strs));Arrays.sort(strs, (o1, o2)-> o2.length() - o1.length());System.out.println(Arrays.toString(strs));}
}

5.Predicate

特点:一个入参(类型由泛型指定),出参为boolean,内含条件判断方法,常用于判断

JDK中的定义如下:

package java.util.function;import java.util.Objects;/*** Represents a predicate (boolean-valued function) of one argument.** <p>This is a <a href="package-summary.html">functional interface</a>* whose functional method is {@link #test(Object)}.** @param <T> the type of the input to the predicate** @since 1.8*/
@FunctionalInterface
public interface Predicate<T> {/*** Evaluates this predicate on the given argument.** @param t the input argument* @return {@code true} if the input argument matches the predicate,* otherwise {@code false}*/boolean test(T t);/*** Returns a composed predicate that represents a short-circuiting logical* AND of this predicate and another.  When evaluating the composed* predicate, if this predicate is {@code false}, then the {@code other}* predicate is not evaluated.** <p>Any exceptions thrown during evaluation of either predicate are relayed* to the caller; if evaluation of this predicate throws an exception, the* {@code other} predicate will not be evaluated.** @param other a predicate that will be logically-ANDed with this*              predicate* @return a composed predicate that represents the short-circuiting logical* AND of this predicate and the {@code other} predicate* @throws NullPointerException if other is null*/default Predicate<T> and(Predicate<? super T> other) {Objects.requireNonNull(other);return (t) -> test(t) && other.test(t);}/*** Returns a predicate that represents the logical negation of this* predicate.** @return a predicate that represents the logical negation of this* predicate*/default Predicate<T> negate() {return (t) -> !test(t);}/*** Returns a composed predicate that represents a short-circuiting logical* OR of this predicate and another.  When evaluating the composed* predicate, if this predicate is {@code true}, then the {@code other}* predicate is not evaluated.** <p>Any exceptions thrown during evaluation of either predicate are relayed* to the caller; if evaluation of this predicate throws an exception, the* {@code other} predicate will not be evaluated.** @param other a predicate that will be logically-ORed with this*              predicate* @return a composed predicate that represents the short-circuiting logical* OR of this predicate and the {@code other} predicate* @throws NullPointerException if other is null*/default Predicate<T> or(Predicate<? super T> other) {Objects.requireNonNull(other);return (t) -> test(t) || other.test(t);}/*** Returns a predicate that tests if two arguments are equal according* to {@link Objects#equals(Object, Object)}.** @param <T> the type of arguments to the predicate* @param targetRef the object reference with which to compare for equality,*               which may be {@code null}* @return a predicate that tests if two arguments are equal according* to {@link Objects#equals(Object, Object)}*/static <T> Predicate<T> isEqual(Object targetRef) {return (null == targetRef)? Objects::isNull: object -> targetRef.equals(object);}
}

简单用法

import java.util.function.Predicate;public class PredicateLambda {public static void main(String[] args) {andMethod(s->s.contains("W"),s-> s.contains("H"));orMethod(s->s.contains("W"),s-> s.contains("H"));negateMethod(s->s.length()>5);}static void andMethod(Predicate<String> first, Predicate<String> second) {boolean isValid = first.and(second).test("helloWorld");System.out.println("字符串符合要求吗:" + isValid);}static void orMethod(Predicate<String> first, Predicate<String> second) {boolean isValid = first.or(second).test("helloWorld");System.out.println("字符串符合要求吗:" + isValid);}static void negateMethod(Predicate<String> predicate) {boolean tooLong = predicate.negate().test("helloWorld");System.out.println("字符串特别长吗:" + tooLong);}

6.Function

特点:一个入参,有出参,入参和出参的类型都由泛型指定,可以多次处理(从第一个开始处理,然后把返回值作为第二个、第三个。。。的结果)

它的实例应该是具备某种功能的  

简单使用如下:

import java.util.function.Function;public class FunctionLambda {public static void main(String[] args) {method(str-> Integer.parseInt(str) + 10,strInt -> strInt *= 10);String str = "zhangsan,80";int age = getAgeNum(str,s->s.split(",")[1],s->Integer.parseInt(s),i-> i -= 10);System.out.println("zhangsan十年前的年龄是:" + age);}static void method(Function<String, Integer> first, Function<Integer, Integer> second) {int num = first.andThen(second).apply("10");System.out.println(num);}static int getAgeNum(String str, Function<String, String> first,Function<String, Integer> second,Function<Integer, Integer> third) {return first.andThen(second).andThen(third).apply(str);}
}

相关文章:

Lambda-常见的函数式接口

如果需要使用Lambda接口&#xff0c;就必须要有一个函数式接口 函数式接口是有且仅有一个抽象方法的接口, 对应的注解是FunctionalInterface Java中内置的常见函数式接口如下: 1.Runnable/ Callable /*** The <code>Runnable</code> interface should be implem…...

P1196 [NOI2002] 银河英雄传说 带权并查集

[NOI2002] 银河英雄传说 题目背景 公元 580158015801 年&#xff0c;地球居民迁至金牛座 α\alphaα 第二行星&#xff0c;在那里发表银河联邦创立宣言&#xff0c;同年改元为宇宙历元年&#xff0c;并开始向银河系深处拓展。 宇宙历 799799799 年&#xff0c;银河系的两大军…...

【项目实战】快来入门Groovy的基础语法吧

一、Groovy是什么? 1.1 与Java语言的关系 下一代的Java 语言,增强Java平台的唯一的脚本语言跟java一样,它也运行在 JVM 中。支持Java平台,无缝的集成了Java 的类和库;Groovy是一种运行在JVM上的动态语言,跑在JVM中的另一种语言编译后的.groovy也是以class的形式出现的。1…...

Mybatis中的动态SQL

Mybatis中的动态SQL 当存在多条件查询的SQL时&#xff0c;当用户某个条件的属性没有写时&#xff0c;就会存在问题&#xff0c;在test中则不能很好的运行 所以Mybatis提出了动态SQL。 即判断用户是否输入了某个属性 动态SQL中的一些问题 方法一 这个里的and是为了确保if条…...

VUE常用API

1.$set数据变了&#xff0c;视图没变 this.$set(targe&#xff0c;key&#xff0c;value)2.$nextTick:返回参数[函数]。是一个异步的&#xff0c;功能获得更新后DOM$nextTick(callback){return Promise.resolve().then(()>{callback();}) }3.$refs获取dom4.$el获取当前组件根…...

25 openEuler管理网络-使用nmcli命令配置ip

文章目录25 openEuler管理网络-使用nmcli命令配置ip25.1 nmcli介绍25.2 设备管理25.2.1 连接到设备25.2.2 断开设备连接25.3 设置网络连接25.3.1 配置动态IP连接25.3.1.1 配置IP25.3.1.2 激活连接并检查状态25.3.2 配置静态IP连接25.3.2.1 配置IP25.3.2.2 激活连接并检查状态25…...

如何安装和使用A-ops工具?

一、pip配置 1.配置信任域 ​ pip3 config set global.trusted-host mirrors.tools.huawei.com2.配置pip源的url地址pip3 config set global.index-url http://mirrors.tools.huawei.com/pypi/simple 二、npm安装及配置 npm -v检测系统有无安装npm,如果没有的话需要配置ope…...

MySql数据库环境部署

MySql基础与Sql数据库概述基础环境的建立MYSQL数据库的连接方法MySql的默认数据库数据库端口号数据库概述 数据库&#xff08;DataBase&#xff0c;DB)∶存储在磁带、磁盘、光盘或其他外存介质上、按定结构组织在一起的相关数据的集合。数据库管理系统〈DataBase Management S…...

极品笔记,阿里P7爆款《K8s+Jenkins》技术笔记,职场必备

前些日子从阿里的朋友那里取得这两份K8sJenkins的爆款技术笔记&#xff1a;《K8S(kubernetes)学习指南》《Jenkins持续集成从入门到精通》&#xff0c;非常高质量的干货&#xff0c;我立马收藏&#xff01; 而今天咱们文章的主角就是这非常之干货的技术笔记&#xff1a;K8SJenk…...

数据结构:各种排序方法的综合比较

排序方法的选用应视具体场合而定。一般情况下考虑的原则有:(1)待排序的记录个数 n;(2)记录本身的大小;(3)关键字的分布情况:(4)对排序稳定性的要求等。 1.时间性能 (1) 按平均的时间性能来分,有三类排序方法: 时间复杂度为 O(nlogn)的方法有:快速排序、堆排序和归并排序,其中…...

【设计模式】 策略模式介绍及C代码实现

【设计模式】 策略模式介绍及C代码实现 背景 在软件构建过程中&#xff0c;某些对象使用的算法可能多种多样&#xff0c;经常改变&#xff0c;如果将这些算法都编码到对象中&#xff0c;将会使对象变得异常复杂&#xff0c;而且有时候支持不使用的算法也是一个性能负担。 如何…...

【数据库】第二章 关系数据库

第二章 关系数据库 2.1关系数据结构及形式化定义 关系 域&#xff08;domain) :域是一组具有相同数据类型的值的集合&#xff0c;可以取值的个数叫基数 笛卡尔积 &#xff1a;一个记录叫做一个元组&#xff08;tuple),元组中每一个属性值&#xff0c;叫一个分量 基数&…...

oracle和mysql的分页

oracle的分页&#xff1a;rownum 注意:&#xff1a; 对 ROWNUM 只能使用 < 或 <, 用 、 >、 > 都不能返回任何数据。 rownum是对结果集的编序排列&#xff0c;始终是从1开始&#xff0c;所以rownum直接使用时不允许使用>、> 所以当查询中间部分的信息时&…...

深拷贝与浅拷贝的理解

浅拷贝的理解浅拷贝的话只会拷贝基本数据类型&#xff0c;例如像string、Number等这些&#xff0c;类似&#xff1a;Object、Array 这类的话拷贝的就是对象的一个指针(通俗来讲就是拷贝一个引用地址&#xff0c;指向的是一个内存同一份数据)&#xff0c;也就是说当拷贝的对象数…...

Shell变量

一、变量分类 根据作用域分三种 &#xff08;一&#xff09;只在函数内有效&#xff0c;叫局部变量 &#xff08;二&#xff09;只在当前shell进程中有效&#xff0c;叫做全局变量 &#xff08;三&#xff09;在当前shell进程与子进程中都有效&#xff0c;叫做环境变量 shell进…...

Android 8请求权限时弹窗BUG

弹窗BUG 应用使用requestPermissions申请权限时&#xff0c;系统会弹出一个选择窗口&#xff0c;可进行允许或拒绝&#xff0c; 此窗口中有一个”不再询问“的选择框&#xff0c; ”拒绝”及“允许”的按钮。 遇到一个Bug,单点击“不再询问”&#xff0c;“允许”这个按钮会变…...

路漫漫:网络空间的监管趋势

网络空间是“以相互依存的网络基础设施为基本架构&#xff0c;以代码、信息与数据的流动为环境&#xff0c;人类利用信息通讯技术与应用开展活动&#xff0c;并与其他空间高度融合与互动的空间”。随着信息化技术的发展&#xff0c;网络空间日益演绎成为与现实人类生存空间并存…...

洛谷 P1208 [USACO1.3]混合牛奶 Mixing Milk

最后水一篇水题题解&#xff08;实在太水了&#xff09; # [USACO1.3]混合牛奶 Mixing Milk ## 题目描述 由于乳制品产业利润很低&#xff0c;所以降低原材料&#xff08;牛奶&#xff09;价格就变得十分重要。帮助 Marry 乳业找到最优的牛奶采购方案。 Marry 乳业从一些奶农手…...

数据库的基本查询

注意&#xff1a;LIMIT的两个参数&#xff0c;第一个是起始位置&#xff0c;第二个是一次查询到多少页。注意&#xff1a;什么类型的数字都是可以排序的。日期的降序是从现在到以前&#xff0c;MySQL ENUM值如何排序&#xff1f;在MYSQL中&#xff0c;我们知道每个ENUM值都与一…...

10 分钟把你的 Web 应用转为桌面端应用

在桌面端应用上&#xff0c;Electron 也早已做大做强&#xff0c;GitHub桌面端、VSCode、Figma、Notion、飞书、剪映、得物都基于此。但最近后起之秀的 Tauri 也引人注目&#xff0c;它解决了 Electron 一个大的痛点——打包产物特别大。 我们知道 Electron 基于谷歌内核 Chro…...

零门槛NAS搭建:WinNAS如何让普通电脑秒变私有云?

一、核心优势&#xff1a;专为Windows用户设计的极简NAS WinNAS由深圳耘想存储科技开发&#xff0c;是一款收费低廉但功能全面的Windows NAS工具&#xff0c;主打“无学习成本部署” 。与其他NAS软件相比&#xff0c;其优势在于&#xff1a; 无需硬件改造&#xff1a;将任意W…...

连锁超市冷库节能解决方案:如何实现超市降本增效

在连锁超市冷库运营中&#xff0c;高能耗、设备损耗快、人工管理低效等问题长期困扰企业。御控冷库节能解决方案通过智能控制化霜、按需化霜、实时监控、故障诊断、自动预警、远程控制开关六大核心技术&#xff0c;实现年省电费15%-60%&#xff0c;且不改动原有装备、安装快捷、…...

新能源汽车智慧充电桩管理方案:新能源充电桩散热问题及消防安全监管方案

随着新能源汽车的快速普及&#xff0c;充电桩作为核心配套设施&#xff0c;其安全性与可靠性备受关注。然而&#xff0c;在高温、高负荷运行环境下&#xff0c;充电桩的散热问题与消防安全隐患日益凸显&#xff0c;成为制约行业发展的关键瓶颈。 如何通过智慧化管理手段优化散…...

相机Camera日志分析之三十一:高通Camx HAL十种流程基础分析关键字汇总(后续持续更新中)

【关注我,后续持续新增专题博文,谢谢!!!】 上一篇我们讲了:有对最普通的场景进行各个日志注释讲解,但相机场景太多,日志差异也巨大。后面将展示各种场景下的日志。 通过notepad++打开场景下的日志,通过下列分类关键字搜索,即可清晰的分析不同场景的相机运行流程差异…...

AI+无人机如何守护濒危物种?YOLOv8实现95%精准识别

【导读】 野生动物监测在理解和保护生态系统中发挥着至关重要的作用。然而&#xff0c;传统的野生动物观察方法往往耗时耗力、成本高昂且范围有限。无人机的出现为野生动物监测提供了有前景的替代方案&#xff0c;能够实现大范围覆盖并远程采集数据。尽管具备这些优势&#xf…...

MFC 抛体运动模拟:常见问题解决与界面美化

在 MFC 中开发抛体运动模拟程序时,我们常遇到 轨迹残留、无效刷新、视觉单调、物理逻辑瑕疵 等问题。本文将针对这些痛点,详细解析原因并提供解决方案,同时兼顾界面美化,让模拟效果更专业、更高效。 问题一:历史轨迹与小球残影残留 现象 小球运动后,历史位置的 “残影”…...

适应性Java用于现代 API:REST、GraphQL 和事件驱动

在快速发展的软件开发领域&#xff0c;REST、GraphQL 和事件驱动架构等新的 API 标准对于构建可扩展、高效的系统至关重要。Java 在现代 API 方面以其在企业应用中的稳定性而闻名&#xff0c;不断适应这些现代范式的需求。随着不断发展的生态系统&#xff0c;Java 在现代 API 方…...

windows系统MySQL安装文档

概览&#xff1a;本文讨论了MySQL的安装、使用过程中涉及的解压、配置、初始化、注册服务、启动、修改密码、登录、退出以及卸载等相关内容&#xff0c;为学习者提供全面的操作指导。关键要点包括&#xff1a; 解压 &#xff1a;下载完成后解压压缩包&#xff0c;得到MySQL 8.…...

AI语音助手的Python实现

引言 语音助手(如小爱同学、Siri)通过语音识别、自然语言处理(NLP)和语音合成技术,为用户提供直观、高效的交互体验。随着人工智能的普及,Python开发者可以利用开源库和AI模型,快速构建自定义语音助手。本文由浅入深,详细介绍如何使用Python开发AI语音助手,涵盖基础功…...

SpringAI实战:ChatModel智能对话全解

一、引言&#xff1a;Spring AI 与 Chat Model 的核心价值 &#x1f680; 在 Java 生态中集成大模型能力&#xff0c;Spring AI 提供了高效的解决方案 &#x1f916;。其中 Chat Model 作为核心交互组件&#xff0c;通过标准化接口简化了与大语言模型&#xff08;LLM&#xff0…...