【个人技术经验及开发技巧分享】 【个人技术经验及开发技巧分享】
首页
  • 操作系统初识
  • JAVA基础
  • JVM
  • 开发框架
  • Redis
  • Zookeeper
  • 消息中间件
  • 持久化
  • 算法
  • 网络
  • 系统架构
  • 并发编程
  • 框架
  • 开发杂货
  • 线上排查
  • 技巧备忘
  • 部署指南
  • 版本管理
  • 工作流程
  • 发版流程
  • 友情链接
  • 网站备忘
  • 在线工具
  • 学习
  • 各种云
  • 应用下载

Louis

首页
  • 操作系统初识
  • JAVA基础
  • JVM
  • 开发框架
  • Redis
  • Zookeeper
  • 消息中间件
  • 持久化
  • 算法
  • 网络
  • 系统架构
  • 并发编程
  • 框架
  • 开发杂货
  • 线上排查
  • 技巧备忘
  • 部署指南
  • 版本管理
  • 工作流程
  • 发版流程
  • 友情链接
  • 网站备忘
  • 在线工具
  • 学习
  • 各种云
  • 应用下载
  • 开发杂货

    • ES查询压测
    • Spring Cloud Stream
    • 线上Tomcat配置参考
    • 配置Prometheus及健康检测
    • Feign支持BasicAuth验证
    • Feign远程调用
    • Hystrix单方法熔断配置
    • 邮件发送自定义Excel
    • 本地开发联调配置
    • RabbitMQ配置备忘
    • Nacos配置中心
    • Java代码杂记
      • 1 stream常见用法
      • 2 类相同属性比较
      • 3 驼峰字符串转下划线字符串
      • 4 Java输入输出流的互相转换
    • Oracle脚本备忘
    • Mysql并发数与连接数
    • 批量算费本地工具类
    • Apollo配置模糊查询
    • 异步任务AsyncIAE
    • 生产环境机器配置参考
  • 线上排查

  • 技巧备忘

  • 部署指南

  • 技术应用
  • 开发杂货
luoxiaofeng
2022-05-11
目录

Java代码杂记

# 1 stream常见用法

List<DTO> 转 List<String>

List<String> ids = dtos.stream()
                        .map(DTO::getId)
                        .distinct()
                        .collect(Collectors.toList());
1
2
3
4

List<DTO> 转 Map<String, List<DTO>>

Map<String, List<DTO>> map = dtos.stream()
                                  .collect(Collectors.groupingBy(DTO::getId));
1
2

List<DTO> 转 Map<key, value>

Map<Integer,String> map = dtos.stream()
                               .collect(Collectors.toMap(DTO::getId, DTO::getName));
1
2

注意

如果值为空,会报空指针异常,可采用以下方法实现转Map。

Map<String, String> map = dtos.stream().collect(
        HashMap::new, 
        (map, dto) -> map.put(dto.getId(), dto.getName()), 
        HashMap::putAll);
1
2
3
4

List<DTO> 转 Map<key, DTO>

// 指定key-value,value是对象本身。
// Function.identity()是简洁写法,也是返回对象本身。
// key冲突的解决办法,这里选择第二个key覆盖第一个key
Map<Integer, DTO> map = dtos.stream()
                            .collect(
                                Collectors.toMap(
                                    DTO::getId, Function.identity(), (key1,key2)->key2
                                )
                             );
1
2
3
4
5
6
7
8
9

List<DTO> 转 String拼接

String str = dtos.stream()
                  .map(DTO::getId)
                  .collect(Collectors.joining(","));
1
2
3

List<DTO> 求和

// 使用mapToInteger、mapToDouble等

Integer returnCount = dtos.stream()
                           .mapToInteger(DTO::getNum)
                           .sum(); 

Double returnCount = dtos.stream()
                          .mapToDouble(DTO::getNum)
                          .sum();
1
2
3
4
5
6
7
8
9

List<DTO> 排序

// 使用mapToInteger、mapToDouble等

List<DTO> newDTOS = dtos.stream()
                        .sorted(Comparator.comparing(DTO::getSortNum, Comparator.reverseOrder()))
                        .collect(Collectors.toList()); 

1
2
3
4
5
6

# 2 类相同属性比较

public class Test {
  public static void main(String[]args)throws NoSuchFieldException {
    Map<String, String> map1 = new HashMap<>();
    Field[] fields = OmsOrderApiVO.class.getDeclaredFields();
    for (Field field : fields) {
      String fieldName = field.getName();
      ApiModelProperty annotation = field.getAnnotation(ApiModelProperty.class);
      String val = "-";
      if (annotation != null) {
        val = annotation.value();
      }
      map1.put(fieldName, val);
    }

    Map<String, String> map2 = new HashMap<>();
    Field[] fields2 = OmsWaybillApiDTO.class.getDeclaredFields();
    for (Field field2 : fields2) {
      String fieldName = field2.getName();
      ApiModelProperty annotation = field2.getAnnotation(ApiModelProperty.class);
      String val = "-";
      if (annotation != null) {
        val = annotation.value();
      }
      map2.put(fieldName, val);
    }
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

# 3 驼峰字符串转下划线字符串

public class Test {
  public static void main(String[] args) throws NoSuchFieldException {
    Map<String, String> map1 = new HashMap<>();
    Field[] fields = SpmCashBillDetail.class.getDeclaredFields();
    for (Field field : fields) {
      String fieldName = field.getName();
      System.out.println(toUnderlineCase(fieldName).toUpperCase());
    }
  }

  public static String toUnderlineCase(String camelCaseStr) {
    if (camelCaseStr == null) {
      return null;
    }
    // 将驼峰字符串转换成数组
    char[] charArray = camelCaseStr.toCharArray();
    StringBuffer buffer = new StringBuffer();
    //处理字符串
    for (int i = 0, l = charArray.length; i < l; i++) {
      if (charArray[i] >= 65 && charArray[i] <= 90) {
        buffer.append("_").append(charArray[i] += 32);
      } else {
        buffer.append(charArray[i]);
      }
    }
    return buffer.toString();
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

# 4 Java输入输出流的互相转换

public class Test {
  File file = new File("D:\\test\\1.txt");
  BufferedInputStream bis = null;
  ByteArrayOutputStream arrayOutputStream = null;
  OutputStream bos = null;
  try {
    // 模拟读入一个文件,作为输入流
    bis = new BufferedInputStream(new FileInputStream(file), 1024);
    // 创建ByteArray输出流,所有的输出可以输出到ByteArray中,可以替代一个文件
    arrayOutputStream = new ByteArrayOutputStream();
    //用buffered包装一下,为了提高效率使用缓冲区流
    bos = new BufferedOutputStream(arrayOutputStream);

    int len = -1;
    //读取文件输入流,写入到输出流ByteArray中,输入流转成了输出流
    byte[] buf = new byte[1024];
    while ((len = bis.read(buf)) != -1) {
      bos.write(buf, 0, len);
    }
    bos.flush();//清空缓冲区(非必要)
    //创建ByteArrayResource用ByteArray输出流的字节数组
    InputStreamSource inputStreamSource = new ByteArrayResource(arrayOutputStream.toByteArray());
    //至此把OutputStream已经转换成了InputStreamSource,输出流又转成了输入流
    // 又将输入流转成了输出流
    BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStreamSource.getInputStream());
    int bytesRead;
    byte[] buffer = new byte[4096];
    while ((bytesRead = bufferedInputStream.read(buffer)) != -1) {
      // 将文件发送到客户端
      bos.write(buffer, 0, bytesRead);
      bos.flush();
    }
  } catch(Exception e) {
    System.out.println(e);
  } finally {
    if (bos != null) {
      bos.close();//关闭BufferedOutputStream输出流
    }
    if (arrayOutputStream != null) {
      arrayOutputStream.close();//关闭ByteArray输出流
    }
    if (bis != null) {
      bis.close();
    }
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
Nacos配置中心
Oracle脚本备忘

← Nacos配置中心 Oracle脚本备忘→

最近更新
01
SpringBoot
10-21
02
Spring
10-20
03
Sentinel
10-14
更多文章>
Copyright © 2022-2023 Louis | 粤ICP备2022060093号-1
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式