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

端杂七杂八系列篇四-Java8篇

后端杂七杂八系列篇四-Java8篇

  • ① Lombok插件
    • ① @RequiredArgsConstructor
    • ② @SneakyThrows
    • ③ @UtilityClass
    • ④ @Cleanup
  • ② Lambda 4个常用的内置函数
    • ① Function<T, R> - 接受一个输入参数并返回一个结果
    • ② Consumer - 接受一个输入参数,并执行某种操作(无返回值)
    • ③ Supplier - 不接受任何参数,但产生一个结果
    • ④ Predicate - 接受一个输入参数并返回一个布尔值
  • ③ Optional
  • ④ 常用Stream流
    • stream 中间操作
    • stream 终端操作
  • Java 8中的Future和CompletableFuture
    • Future
    • CompletableFuture

① Lombok插件

Lombok是一个可以通过简单的注解的形式来帮助我们简化消除一些必须有但显得很臃肿的 Java 代码的工具。

① @RequiredArgsConstructor

在这里插入图片描述

② @SneakyThrows

在 Java 中,异常被分为了受查异常 (checked exception)和 非受查异常(unchecked exception)两种。
非受查异常又叫运行时异常,即 RuntimeException。
受查异常,即 Exception。

受查异常是Java给你检查的异常,需要你手动try catch

比如这个,写的时候会报错,IDE会提示我们需要加上try catch

在这里插入图片描述

运行时异常是Java 运行时候报出来的异常,一般是我们程序员写错了。


我们的@SneakyThrows就是为了让我们少写try catch 代码, 即在有受查异常的时候,我们加上注解,就不用写try catch了。


代码举例

import lombok.SneakyThrows;public class SneakyThrowsDemo {// 使用注解@SneakyThrowspublic String readFile(String filePath) {File file = new File(filePath);BufferedReader reader = new BufferedReader(new FileReader(file));StringBuilder content = new StringBuilder();String line;while ((line = reader.readLine()) != null) {content.append(line).append("\n");}reader.close();return content.toString();}// 不使用注解public String readFileWithout(String filePath) {try{File file = new File(filePath);BufferedReader reader = new BufferedReader(new FileReader(file));StringBuilder content = new StringBuilder();String line;while ((line = reader.readLine()) != null) {content.append(line).append("\n");}reader.close();return content.toString();}catch(e){}}public static void main(String[] args) {SneakyThrowsDemo demo = new SneakyThrowsDemo();// 无需捕获FileNotFoundException和IOExceptionSystem.out.println(demo.readFile("example.txt"));}
}

③ @UtilityClass

用于定义工具类的时候,不用定义static的方法了。

在这里插入图片描述

举个例子

public class UtilClass {// 静态变量,全局存储public static int globalCount = 0;// 静态方法,可以直接通过类名调用,无需创建对象public static void incrementCount() {globalCount++;}// 其他静态工具方法public static String formatString(String input) {return "Formatted: " + input.toUpperCase();}// 使用示例:public static void main(String[] args) {// 不需要创建UtilClass对象,直接访问静态成员UtilClass.incrementCount();System.out.println(UtilClass.globalCount); // 输出:1String formattedString = UtilClass.formatString("hello world");System.out.println(formattedString); // 输出:Formatted: HELLO WORLD}
}

在Java中,静态工具类中的属性默认情况下是可以一直保留的,除非显式地进行修改或者JVM垃圾回收机制清除了该类的Class对象(这在正常应用中非常罕见)。

在这里插入图片描述
在这里插入图片描述


使用注解时候的demo

@UtilityClass
public class WxMpContextHolder {private final ThreadLocal<String> THREAD_LOCAL_APPID = new TransmittableThreadLocal<>();/*** TTL 设置appId* @param appId*/public void setAppId(String appId) {THREAD_LOCAL_APPID.set(appId);}/*** 获取TTL中的appId* @return*/public String getAppId() {return THREAD_LOCAL_APPID.get();}public void clear() {THREAD_LOCAL_APPID.remove();}}

④ @Cleanup

>

// Java 标准的写法public class CleanupExample {public static void main(String[] args) throws IOException {InputStream in = new FileInputStream(args[0]);try {OutputStream out = new FileOutputStream(args[1]);try {byte[] b = new byte[10000];while (true) {int r = in.read(b);if (r == -1) break;out.write(b, 0, r);}} finally {if (out != null) {out.close();}}} finally {if (in != null) {in.close();}}}
}// 注解的写法
public class CleanupExample {public static void main(String[] args) throws IOException {@Cleanup InputStream in = new FileInputStream(args[0]);@Cleanup OutputStream out = new FileOutputStream(args[1]);byte[] b = new byte[10000];while (true) {int r = in.read(b);if (r == -1) break;out.write(b, 0, r);}}
}

② Lambda 4个常用的内置函数

① Function<T, R> - 接受一个输入参数并返回一个结果

public class FunctionDemo {public static void main(String[] args) {List<String> names = Arrays.asList("Alice", "Bob", "Charlie");// 使用lambda表达式转换字符串为大写Function<String, String> toUpperCase = s -> s.toUpperCase();names.stream().map(toUpperCase).forEach(System.out::println);}
}

② Consumer - 接受一个输入参数,并执行某种操作(无返回值)

public class ConsumerDemo {public static void main(String[] args) {List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);// 使用lambda表达式打印数字Consumer<Integer> printNumber = n -> System.out.println("Number: " + n);numbers.forEach(printNumber);}
}

③ Supplier - 不接受任何参数,但产生一个结果

public class SupplierDemo {public static void main(String[] args) {// 使用lambda表达式生成随机数Supplier<Integer> randomIntSupplier = () -> (int) (Math.random() * 100);System.out.println("Random number: " + randomIntSupplier.get());}
}

④ Predicate - 接受一个输入参数并返回一个布尔值

public class PredicateDemo {public static void main(String[] args) {List<String> fruits = Arrays.asList("Apple", "Banana", "Cherry", "Durian");// 使用lambda表达式检查字符串长度是否大于5个字符Predicate<String> isLongFruit = fruit -> fruit.length() > 5;fruits.stream().filter(isLongFruit).forEach(System.out::println);}
}

③ Optional

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

用法例子一

public class Student {private String name;private int age;private Integer score;//省略 construct get set
}public List<Student> initData(){Student s1 = new Student("张三", 19, 80);Student s2 = new Student("李四", 19, 50);Student s3 = new Student("王五", 23, null);Student s4 = new Student("赵六", 16, 90);Student s5 = new Student("钱七", 18, 99);Student s6 = new Student("孙八", 20, 40);Student s7 = new Student("吴九", 21, 88);return Arrays.asList(s1, s2, s3, s4, s5, s6, s7);
}@Test
public void beforeJava8() {List<Student> studentList = initData();for (Student student : studentList) {if (student != null) {if (student.getAge() >= 18) {Integer score = student.getScore();if (score != null && score > 80) {System.out.println("入选:" + student.getName());}}}}
}@Test
public void useJava8() {List<Student> studentList = initData();for (Student student : studentList) {Optional<Student> studentOptional = Optional.of(student);Integer score = studentOptional.filter(s -> s.getAge() >= 18).map(Student::getScore).orElse(0);if (score > 80) {System.out.println("入选:" + student.getName());}}
}

用法例子二

public String test0(AlarmAllParmeter alarmAllParmeter) {String errorResult = "";if (null != alarmAllParmeter) {Integer alarmId = alarmAllParmeter.getAlarmEventInputId();if (null != alarmId) {AlarmEventInput alarmEventInput = alarmEventInputService.get(alarmId);if (null != alarmEventInput) {String alarmName = alarmEventInput.getAlarmName();int alarmType = alarmEventInput.getAlarmType();return String.valueOf(alarmType) + "-" + alarmName;} else {return errorResult;}} else {return errorResult;}} else {return errorResult;}}// 改进方案一public String test1(AlarmAllParmeter alarmAllParmeter){String errorResult = "";Optional<AlarmAllParmeter> op = Optional.ofNullable(alarmAllParmeter);if(op.isPresent()){Integer alarmId = op.get().getAlarmEventInputId();Optional<Integer> op1 = Optional.ofNullable(alarmId);if(op1.isPresent()){AlarmEventInput alarmEventInput = alarmEventInputService.get(op1.get());Optional<AlarmEventInput> op2 = Optional.ofNullable(alarmEventInput);if (op2.isPresent()) {String alarmName = alarmEventInput.getAlarmName();int alarmType = alarmEventInput.getAlarmType();return String.valueOf(alarmType) + "-" + alarmName;} else {return errorResult;}}else {return errorResult;}}else {return errorResult;}}// 改进方案二
public String test2(AlarmAllParmeter alarmAllParmeter){return Optional.ofNullable(alarmAllParmeter).map(a -> a.getAlarmEventInputId()).map(a -> alarmEventInputService.get(a)).map(a -> String.valueOf(a.getAlarmType())+"-"+a.getAlarmName()).orElse("");}

④ 常用Stream流

在这里插入图片描述

在这里插入图片描述

stream 中间操作


在这里插入图片描述

// filter
List<Person> result = list.stream().filter(Person::isStudent).collect(toList());// distinct
List<Person> result = list.stream().distinct().collect(toList());// limit
List<Person> result = list.stream().limit(3).collect(toList());// skip
List<Person> result = list.stream().skip(3).collect(toList());// map
List<String> result = list.stream().map(Person::getName).collect(toList());

stream 终端操作


在这里插入图片描述

// anyMatch
boolean result = list.stream().anyMatch(Person::isStudent);// allMatch
boolean result = list.stream().allMatch(Person::isStudent);// noneMatch
boolean result = list.stream().noneMatch(Person::isStudent);// findAny
Optional<Person> person = list.stream().findAny();// findFirst
Optional<Person> person = list.stream().findFirst();

Java 8中的Future和CompletableFuture

在这里插入图片描述
在这里插入图片描述

Future


用法demo

public class FutureExample {public static void main(String[] args) throws ExecutionException, InterruptedException {// 创建一个线程池ExecutorService executor = Executors.newSingleThreadExecutor();// 提交一个Callable任务到线程池,返回一个Future对象Future<String> future = executor.submit(new Callable<String>() {@Overridepublic String call() throws Exception {Thread.sleep(2000); // 模拟耗时操作return "Hello from Future!";}});// 主线程可以继续执行其他任务,不被阻塞System.out.println("Main thread is doing other tasks...");// 当需要获取结果时,调用Future的get方法,该方法会阻塞直到结果准备好String result = future.get();System.out.println(result);// 关闭线程池executor.shutdown();}
}

CompletableFuture


用法demo

public class CompletableFutureExample {public static void main(String[] args) throws ExecutionException, InterruptedException {// 创建一个CompletableFuture对象并提供一个异步计算的任务CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {try {Thread.sleep(2000); // 模拟耗时操作} catch (InterruptedException e) {Thread.currentThread().interrupt();}return "Hello from CompletableFuture!";});// 使用thenApply方法进行链式处理,将上一步的结果转换为新的结果CompletableFuture<Integer> lengthFuture = future.thenApply(result -> result.length());// 使用thenAccept方法处理完成后的结果,不返回任何值lengthFuture.thenAccept(length -> System.out.println("Length: " + length));// 等待所有任务完成CompletableFuture.allOf(future, lengthFuture).join();// 或者直接获取结果(这会阻塞直到结果准备好)// int length = lengthFuture.get();// System.out.println("Length: " + length);}
}

相关文章:

端杂七杂八系列篇四-Java8篇

后端杂七杂八系列篇四-Java8篇 ① Lombok插件① RequiredArgsConstructor② SneakyThrows③ UtilityClass④ Cleanup ② Lambda 4个常用的内置函数① Function<T, R> - 接受一个输入参数并返回一个结果② Consumer - 接受一个输入参数&#xff0c;并执行某种操作&#xf…...

操作系统一些面试

你这个请求队列是属于一写多读对吧&#xff0c;怎么解决冲突的&#xff1f; 可以采用双buffer或者说双缓冲区&#xff0c;一个缓冲区用来写&#xff0c;一个缓冲区用来读&#xff0c;采用交换指针的方法来进行缓存区的交换&#xff0c;这样交换效率是O(1)的&#xff0c;但是交…...

大语言模型

概念 大语言模型&#xff08;Large Language Model&#xff0c;简称LLM&#xff09;是一种基于人工智能技术的自然语言处理模型&#xff0c;是指在大量数据上训练的高级人工智能算法&#xff0c;以自上文推理词语概率为核心任务。它通过在海量文本数据上进行训练&#xff0c;学…...

php反序列化之pop链构造(基于重庆橙子科技靶场)

常见魔术方法的触发 __construct() //创建类对象时调用 __destruct() //对象被销毁时触发 __call() //在对象中调用不可访问的方法时触发 __callStatic() //在静态方式中调用不可访问的方法时触发 __get() //调用类中不存在变量时触发&#xff08;找有连续箭头的…...

k8s---对外服务 ingress

目录 目录 目录 ingress与service ingress的组成 ingress-controller&#xff1a; ingress暴露服务的方式 2.方式二&#xff1a;DaemonSethostnetworknodeSelector DaemonSethostnetworknodeSelector如何实现 3.deploymentNodePort&#xff1a; 虚拟主机的方式实现http代…...

最优解-最长公共子序列

问题描述 最长公共子序列(Longest Common Subsequence&#xff0c;LCS)即求两个序列最长的公共子序列(可以不连续)。比如3 2 1 4 5和1 2 3 4 5两个序列&#xff0c;最长公共子序列为2 4 5 长度为3。解决这个问题必然要使用动态规划。既然要用到动态规划&#xff0c;就要知道状…...

el-tree获取当前选中节点及其所有父节点的id(包含半选中父节点的id)

如下图,我们现在全勾中的有表格管理及其下的子级,而半勾中的有工作台和任务管理及其子级 现在点击保存按钮后,需要将勾中的节点id及该节点对应的父节点,祖先节点的id(包含半选中父节点的id)也都一并传给后端,那这个例子里就应该共传入9个id,我们可以直接将getCheckedK…...

新上线一个IT公司微信小程序

项目介绍 项目背景: 一家IT公司,业务包含以下六大块: 1、IT设备回收 2、IT设备租赁 3、IT设备销售 4、IT设备维修 5、IT外包 6、IT软件开发 通过小程序,提供在线下单,在线制单,在线销售,业务介绍,推广,会员 项目目的: 业务介绍: 包含企业业务介绍 客户需…...

MCAL配置-PWM(EB23.0)

PWM配置项的介绍 一、General 1、PwmDeInitApi 从代码中添加/删除Pwm_17_GtmCcu6_Delnit() API。 TRUE&#xff1a;Pwm_17_GtmCcu6_Delnit() API可供用户使用。 FALSE&#xff1a;Pwm_17_GtmCcu6_Delnit() API对用户不可用。 注意:默认情况下禁用Pwm_17_GtmCcu6_Delnit() …...

v-if和v-for哪个优先级更高?

v-if和v-for哪个优先级更高&#xff1f; 结论&#xff1a; vue2输出的渲染函数是先执行循环&#xff0c;在看条件判断&#xff0c;如果将v-if和v-for写在一个标签内&#xff0c;哪怕只渲染列表中的一小部分&#xff0c;也要重新遍历整个列表&#xff0c;无形造成资源浪费。vu…...

Mapstruct 常用案例(持续更新.).

将A转换为B Mapper(componentModel "spring") public interface DemoConvert {B A2B(A a); }将List转换为List 注意&#xff1a;以下两个都不可缺少&#xff0c;需要先声明单个和集合的同时生命才可 Mapper(componentModel "spring") public interface …...

QT基础篇(10)QT5网络与通信

QT5网络与通信是指在QT5开发环境中使用网络进行数据传输和通信的相关功能和技术。 QT5提供了一套完善的网络模块&#xff0c;包括了TCP、UDP、HTTP等协议的支持&#xff0c;可以方便地在QT应用程序中进行网络通信。通过QT5的网络模块&#xff0c;开发者可以实现客户端和服务器…...

【Leetcode】269.火星词典(Hard)

一、题目 1、题目描述 现有一种使用英语字母的火星语言,这门语言的字母顺序与英语顺序不同。 给你一个字符串列表 words ,作为这门语言的词典,words 中的字符串已经 按这门新语言的字母顺序进行了排序 。 请你根据该词典还原出此语言中已知的字母顺序,并 按字母递增顺序…...

opencv_模型训练

文件夹 opencv训练文件 xml negdataposdata 说明 negdata目录: 放负样本的目录 posdata目录&#xff1a; 放正样本的目录 xml目录&#xff1a; 新建的一个目录&#xff0c;为之后存放分类器文件使用 neg.txt: 负样本路径列表 pos.txt: 正样本路径列表 pos.vec: 后续自动生成…...

python PyQt5的学习

一、安装与配置 1、环境&#xff1a; python3.7 2、相关模块 pip install pyqt5 pyqt5-tools pyqt5designer 可以加个镜像 -i https://pypi.tuna.tsinghua.edu.cn/simple3、配置设计器 python的pyqt5提供了一个设计器&#xff0c;便于ui的设计 界面是这样的&#xff1a…...

3.goLand基础语法

目录 概述语法for常量与变量数组切片 slice切片问题问题1问题2 Make 和 New结构体和指针结构体标签 结束 概述 从 java 转来学 go &#xff0c;在此记录&#xff0c;方便以后翻阅。 语法 for package mainimport "fmt"func main() {for i : 0; i < 3; i {fmt.…...

计算机硬件 5.2组装整机

第二节 组装整机 一、准备工作 1.常用工具&#xff1a;中号十字螺丝刀、尖嘴钳、软毛刷、防静电手环等。 2.组装原则&#xff1a; ①按“先小后大”“从里到外”的顺序进行&#xff0c;不遗漏每一环节&#xff0c;不“带病”进行下一环节。 ②合理使用工具器材&#xff0c;…...

Docker搭建MySQL主从数据库-亲测有效

1、测试环境概述 1、使用MySQL5.7.35版本 2、使用Centos7操作系统 3、使用Docker20版本 案例中描述了整个测试的详细过程 2、安装Docker 2.1、如果已经安装docker,可以先卸载 yum remove -y docker \ docker-client \ docker-client-latest \ docker-common \ docker-l…...

PyTorch 中的距离函数深度解析:掌握向量间的距离和相似度计算

目录 Pytorch中Distance functions详解 pairwise_distance 用途 用法 参数 数学理论公式 示例代码 cosine_similarity 用途 用法 参数 数学理论 示例代码 输出结果 pdist 用途 用法 参数 数学理论 示例代码 总结 Pytorch中Distance functions详解 pair…...

【Vue技巧】vue3中不支持.sync语法糖的解决方案

海鲸AI-ChatGPT4.0国内站点&#xff0c;支持设计稿转代码&#xff1a;https://www.atalk-ai.com 在 Vue 3 中&#xff0c;.sync 修饰符已经被移除。在 Vue 2 中&#xff0c;.sync 修饰符是一个语法糖&#xff0c;用于简化子组件和父组件之间的双向数据绑定。在 Vue 3 中&#x…...

关于nvm与node.js

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

ardupilot 开发环境eclipse 中import 缺少C++

目录 文章目录 目录摘要1.修复过程摘要 本节主要解决ardupilot 开发环境eclipse 中import 缺少C++,无法导入ardupilot代码,会引起查看不方便的问题。如下图所示 1.修复过程 0.安装ubuntu 软件中自带的eclipse 1.打开eclipse—Help—install new software 2.在 Work with中…...

Redis数据倾斜问题解决

Redis 数据倾斜问题解析与解决方案 什么是 Redis 数据倾斜 Redis 数据倾斜指的是在 Redis 集群中&#xff0c;部分节点存储的数据量或访问量远高于其他节点&#xff0c;导致这些节点负载过高&#xff0c;影响整体性能。 数据倾斜的主要表现 部分节点内存使用率远高于其他节…...

代理篇12|深入理解 Vite中的Proxy接口代理配置

在前端开发中,常常会遇到 跨域请求接口 的情况。为了解决这个问题,Vite 和 Webpack 都提供了 proxy 代理功能,用于将本地开发请求转发到后端服务器。 什么是代理(proxy)? 代理是在开发过程中,前端项目通过开发服务器,将指定的请求“转发”到真实的后端服务器,从而绕…...

OPENCV形态学基础之二腐蚀

一.腐蚀的原理 (图1) 数学表达式&#xff1a;dst(x,y) erode(src(x,y)) min(x,y)src(xx,yy) 腐蚀也是图像形态学的基本功能之一&#xff0c;腐蚀跟膨胀属于反向操作&#xff0c;膨胀是把图像图像变大&#xff0c;而腐蚀就是把图像变小。腐蚀后的图像变小变暗淡。 腐蚀…...

CVE-2020-17519源码分析与漏洞复现(Flink 任意文件读取)

漏洞概览 漏洞名称&#xff1a;Apache Flink REST API 任意文件读取漏洞CVE编号&#xff1a;CVE-2020-17519CVSS评分&#xff1a;7.5影响版本&#xff1a;Apache Flink 1.11.0、1.11.1、1.11.2修复版本&#xff1a;≥ 1.11.3 或 ≥ 1.12.0漏洞类型&#xff1a;路径遍历&#x…...

Linux nano命令的基本使用

参考资料 GNU nanoを使いこなすnano基础 目录 一. 简介二. 文件打开2.1 普通方式打开文件2.2 只读方式打开文件 三. 文件查看3.1 打开文件时&#xff0c;显示行号3.2 翻页查看 四. 文件编辑4.1 Ctrl K 复制 和 Ctrl U 粘贴4.2 Alt/Esc U 撤回 五. 文件保存与退出5.1 Ctrl …...

Kafka主题运维全指南:从基础配置到故障处理

#作者&#xff1a;张桐瑞 文章目录 主题日常管理1. 修改主题分区。2. 修改主题级别参数。3. 变更副本数。4. 修改主题限速。5.主题分区迁移。6. 常见主题错误处理常见错误1&#xff1a;主题删除失败。常见错误2&#xff1a;__consumer_offsets占用太多的磁盘。 主题日常管理 …...

DBLP数据库是什么?

DBLP&#xff08;Digital Bibliography & Library Project&#xff09;Computer Science Bibliography是全球著名的计算机科学出版物的开放书目数据库。DBLP所收录的期刊和会议论文质量较高&#xff0c;数据库文献更新速度很快&#xff0c;很好地反映了国际计算机科学学术研…...

Linux-进程间的通信

1、IPC&#xff1a; Inter Process Communication&#xff08;进程间通信&#xff09;&#xff1a; 由于每个进程在操作系统中有独立的地址空间&#xff0c;它们不能像线程那样直接访问彼此的内存&#xff0c;所以必须通过某种方式进行通信。 常见的 IPC 方式包括&#…...