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

java8 常用code

文章目录

  • 前言
  • 一、lambda
    • 1. 排序
      • 1.1 按照对象属性排序:
      • 1.2 字符串List排序:
      • 1.3 数据库排序jpa
    • 2. 聚合
      • 2.1 基本聚合(返回对象list)
      • 2.2 多字段组合聚合(直接返回对象list数量)
  • 二、基础语法
    • 2.1 List
      • 2.1.1 数组初始化赋值
      • 2.1.2. 逗号分割字符串、list互转
      • 2.1.3 去重
    • 2.2. Json解析
      • 2.2.1 Gson
      • 2.2.2 Fastjson
    • 2.3. LocalDateTime
      • 2.3.1 String->LocalDateTime
      • 2.3.2 Date->LocalDateTime
    • 2.4. Optional
      • 2.4.1 map/flatMap
      • 2.4.2 ifPresent
      • 2.4.3 filter
    • 2.5. EsayExcel
      • 2.5.1 导出示例
      • 2.5.2 相关注解
  • 三、 Linux命令
    • 3.1 磁盘爆满占用情况
    • 3.2 nacos单机启动命令
    • 3.3 防火墙状态查询及操作
    • 3.4 清理缓存(buff/cache)


前言

常用语法汇总

一、lambda

1. 排序

1.1 按照对象属性排序:

List<AccidentEduSLResp> respList =list.stream().sorted(Comparator.comparing(AccidentEduSLResp::getOrgUnit)).collect(Collectors.toList());
district.sort(Comparator.comparing(AccidentEduSLResp::getOrgUnit));  //性能优

1.2 字符串List排序:

List<String> sortedDistrict = district.stream().sorted().collect(Collectors.toList());

1.3 数据库排序jpa

dao.findAll(spec, Sort.by(Sort.Order.desc(ExpertConstants.UPDATE_TIME), Sort.Order.asc(ExpertConstants.EXAMINE_STATUS)));

2. 聚合

2.1 基本聚合(返回对象list)

Map<String, List<AccidentSupervisePO>> collect = cityList.stream().collect(Collectors.groupingBy(s -> s.getDistrictCode()));

2.2 多字段组合聚合(直接返回对象list数量)

Map<String, Long> collect = list.stream().collect(Collectors.groupingBy(o -> o.getDistrictCode() + "_" + o.getOrgUnit(), Collectors.counting()));

二、基础语法

2.1 List

2.1.1 数组初始化赋值

Arrays.asList 不允许add remove操作 UnsupportedOperationException

public static final List CITY_ARR = Arrays.asList("230100","230200","230300","230400","230500","230600");

需要add等操作需要以下写法支持

List<String> list = new ArrayList<>(Arrays.asList(arr));

2.1.2. 逗号分割字符串、list互转

List 转字符串:

Joiner.on(",").join(list)

字符串转List:

//-> 引入guava-28.2-jre.jar//-> CommonConstants常量类定义
public static final Splitter SPLITTER_COMMA = Splitter.on(",").omitEmptyStrings().trimResults();
//需要判断字符串是否为空
List<String> list = CommonConstants.SPLITTER_COMMA.splitToList(a.getDistrictCode());

2.1.3 去重

用hashset去重list 性能优

List<String> testListDistinctResult = new ArrayList<>(new HashSet(testList));

2.2. Json解析

2.2.1 Gson

Book b = new Book("书名1","简介1");
//使用gson将对象转为json字符串
String json = new Gson().toJson(b);
System.out.println(json);//使用gson将json字符转转为对象(第一个参数为json字符串,第二个参数为要转为的类)
Book b2 = new Gson().fromJson("{\\"name\\":\\"书名1\\",\\"info\\":\\"简介1\\"}",Book.class);

2.2.2 Fastjson

Book b = new Book("书名2","简介2");
//使用fastjson将对象转为json字符串
String json= JSON.toJSONString(b);
System.out.println(json);//使用fastjson将json字符转转为对象(第一个参数为json字符串,第二个参数为要转为的类)
Book b2 = JSON.parseObject("{\\"name\\":\\"书名1\\",\\"info\\":\\"简介1\\"}", Book.class);

2.3. LocalDateTime

2.3.1 String->LocalDateTime

//1.具有转换功能的对象
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//2.要转换的对象	
LocalDateTime time = LocalDateTime.now();//3.发动功能
String localTime = df.format(time);
System.out.println("LocalDateTime转成String类型的时间:"+localTime);//3.LocalDate发动,将字符串转换成  df格式的LocalDateTime对象,的功能
LocalDateTime LocalTime = LocalDateTime.parse(strLocalTime,df)
System.out.println("String类型的时间转成LocalDateTime:"+LocalTime);

2.3.2 Date->LocalDateTime

//Date转LocalDateTime 
Date date = new Date();
Instant instant = date.toInstant();
ZoneId zoneId = ZoneId.systemDefault();
LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
System.out.println("Date = " + date);
System.out.println("LocalDateTime = " + localDateTime);//LocalDateTime转Date 
ZoneId zoneId = ZoneId.systemDefault();
LocalDateTime localDateTime = LocalDateTime.now();
ZonedDateTime zdt = localDateTime.atZone(zoneId);
Date date = Date.from(zdt.toInstant());
System.out.println("LocalDateTime = " + localDateTime);
System.out.println("Date = " + date);

2.4. Optional

2.4.1 map/flatMap

● map适用于基础数据类型
● flatMap适用于对象类型
user不为空的时候取address address为空取city city为空异常

Optional.ofNullable(user).map(u-> u.getAddress()).map(a->a.getCity()).orElseThrow(()->new Exception("错误"));

2.4.2 ifPresent

user不为空时dosomething

Optional.ofNullable(user)
.ifPresent(u->{dosomething(u);
});

2.4.3 filter

如果user的name的是zhangsan的,则返回当前对象。否则返回构造的user对象。

Optional.ofNullable(user)
.filter(u->"zhangsan".equals(u.getName()))
.orElseGet(()-> {User user1 = new User();user1.setName("zhangsan");return user1;
});

2.5. EsayExcel

2.5.1 导出示例

response.setContentType("application/octet-stream");
response.setCharacterEncoding("utf-8");
// 这里URLEncoder.encode可以防止中文乱码 当然和easyExcel没有关系
String fileName = URLEncoder.encode("专家报销汇总" + DateUtil.localDateToString(LocalDate.now()), "UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx");
// 前端需要FileName头否则会会有问题
response.setHeader("FileName", fileName + ".xlsx");
response.setHeader("Access-Control-Expose-Headers", "FileName");
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
HorizontalCellStyleStrategy horizontalCellStyleStrategy =
new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
EasyExcel//将数据映射到DownloadDTO实体类并响应到浏览器
.write(response.getOutputStream(), ExpertAndCostInfoOutDTO.class)
//07的excel版本,节省内存
.excelType(ExcelTypeEnum.XLSX)
//是否自动关闭输入流
.autoCloseStream(Boolean.TRUE)
.registerWriteHandler(horizontalCellStyleStrategy)
.sheet("专家报销汇总").doWrite(findExpertAndCostGatherList(dto).getExpertList());

2.5.2 相关注解

//不映射excel
@ExcelIgnore    //列宽 class上控制全部字段  属性上控制该属性字段
@ColumnWidth(40)  //2.1.4 表头名称及排序   
//@ExcelProperty(order = 2)  2.2.7 排序写法 index被兼容
@ExcelProperty(value = "任务内容", index = 1)

三、 Linux命令

3.1 磁盘爆满占用情况

df -h
du -h --max-depth=1

3.2 nacos单机启动命令

sh startup.sh -m standalone

3.3 防火墙状态查询及操作

systemctl stop firewalld
systemctl status firewalld
systemctl disable firewalld

3.4 清理缓存(buff/cache)

清除前后使用 free -h 查看效果

free -h
sysctl -w vm.drop_caches=3
free -h

在这里插入图片描述

相关文章:

  • 【读取流报流关闭错误原因及解决办法】
  • Redis穿透以及解决方法
  • 删除误提交的 git commit
  • python笔记:dtaidistance
  • SAP ABAP 通过右键菜单完成Tree Control 节点的增删改功能
  • 网络安全威胁——中间人攻击
  • Distilling Knowledge via Knowledge Review 中文版
  • 封装PoiExcelUtils
  • GPT-Crawler一键爬虫构建GPTs知识库
  • 吉他初学者学习网站搭建系列(5)——如何做一个在线节拍器
  • Android:BackStackRecord
  • error转string
  • uniapp使用vue-i18n国际化多国语言
  • 记录 | CUDA编程中使用#ifdef指令控制生成CPU和GPU代码
  • [足式机器人]Part2 Dr. CAN学习笔记-数学基础Ch0-3线性化Linearization
  • 08.Android之View事件问题
  • es6(二):字符串的扩展
  • gcc介绍及安装
  • JAVA 学习IO流
  • JavaScript服务器推送技术之 WebSocket
  • JavaSE小实践1:Java爬取斗图网站的所有表情包
  • mongo索引构建
  • Nginx 通过 Lua + Redis 实现动态封禁 IP
  • Otto开发初探——微服务依赖管理新利器
  • python学习笔记-类对象的信息
  • 分享一份非常强势的Android面试题
  • 服务器从安装到部署全过程(二)
  • 聊聊flink的TableFactory
  • 前端面试之CSS3新特性
  • 软件开发学习的5大技巧,你知道吗?
  • 使用 @font-face
  • 思否第一天
  • 小试R空间处理新库sf
  • 用Canvas画一棵二叉树
  • 新年再起“裁员潮”,“钢铁侠”马斯克要一举裁掉SpaceX 600余名员工 ...
  • ​Linux Ubuntu环境下使用docker构建spark运行环境(超级详细)
  • #我与Java虚拟机的故事#连载06:收获颇多的经典之作
  • (NO.00004)iOS实现打砖块游戏(十二):伸缩自如,我是如意金箍棒(上)!
  • (rabbitmq的高级特性)消息可靠性
  • (Repost) Getting Genode with TrustZone on the i.MX
  • (阿里云万网)-域名注册购买实名流程
  • (八)c52学习之旅-中断实验
  • (二)斐波那契Fabonacci函数
  • (附源码)ssm基于微信小程序的疫苗管理系统 毕业设计 092354
  • (九)信息融合方式简介
  • . ./ bash dash source 这五种执行shell脚本方式 区别
  • .net 7 上传文件踩坑
  • .NET 8 编写 LiteDB vs SQLite 数据库 CRUD 接口性能测试(准备篇)
  • .net core 连接数据库,通过数据库生成Modell
  • .net MVC中使用angularJs刷新页面数据列表
  • .NET业务框架的构建
  • /etc/fstab 只读无法修改的解决办法
  • [ 隧道技术 ] 反弹shell的集中常见方式(四)python反弹shell
  • [AutoSar]BSW_Memory_Stack_003 NVM与APP的显式和隐式同步
  • [BetterExplained]书写是为了更好的思考(转载)