Java8新特性一点通 | 回顾字符转日期&JoinArray使用
2024-09-05 13:35:26
StringToDate日期转换
Convert string to date in ISO8601 format
- 利用
LocalDate.parse(CharSequence text)
直接以ISO8601方式格式化
- 利用
String originalDate = "2018-08-07";
LocalDate localDate = LocalDate.parse(originalDate);
System.out.println("Date:"+localDate);
Output:
Date:2018-08-07
- Convert string to date in custom formats
- 利用
DateTimeFormatter.ofPattern(String pattern)
和LocalDate.parse(CharSequence text, DateTimeFormatter formatter)
结合对日期以指定格式格式化
- 利用
String originalDate1 = "2018-08-07 10:47:00";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
LocalDate localDate1 = LocalDate.parse(originalDate1,formatter);
System.out.println("custom date:"+localDate1);
Output:
custom date:2018-08-07
Join Array使用
对现有数组添加字符串组成新的字符串的几个方法:
- String.join(CharSequence delimiter, CharSequence… elements)
场景:可以对现有数组添加分隔符组成新的字符串
String joinedString = String.join(",", "hello", "world", "!");
System.out.println("示例1:" + joinedString);
Output:
示例1:hello,world,!
String.join(CharSequence delimiter, Iterable elements)
场景:可以对现有列表添加分隔符组成新的字符串
List<String> strList = Arrays.asList("hello", "world", "!");
String joinedString1 = String.join(",", strList);
System.out.println("示例2:" + joinedString1);
Output:
示例2:hello,world,!
StringJoiner(CharSequence delimiter)
场景:添加分隔符
StringJoiner stringJoiner1 = new StringJoiner(",");
stringJoiner1.add("hello").add("world").add("!");
System.out.println("示例3:" + stringJoiner1.toString());
Output:
示例3:hello,world,!
StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix)
场景:添加分隔符以及前后缀
StringJoiner stringJoiner2 = new StringJoiner(",", "[", "]");
stringJoiner2.add("hello").add("world").add("!");
System.out.println("示例4:" + stringJoiner2.toString());
Output:
示例4:[hello,world,!]
Collectors.joining
场景:在lambda表达式里面用,针对添加分隔符和前后缀的场景
List<String> strList1 = Arrays.asList("hello", "world", "!");
String joinedString3 = strList1.stream().collect(Collectors.joining(",","[","]"));
System.out.println("示例5:"+joinedString3);
Output:
示例5:[hello,world,!]
StringUtils.join()
场景:跟以上用法差不多,使用工具类去把数据和列表组成单独的字符串
String[] strArray = {"hello", "world", "!"};
String joinedString4 = StringUtils.join(strArray, ",");
System.out.println("示例6:" + joinedString4);
Output:
示例6:hello,world,!
最新文章
- Base64加密算法封装
- 分析自定义view的实现过程-实现雪花飞舞效果(转载有改动)
- 漫谈Linux内核哈希表(2)
- 浅谈输入输出”重定向“——基于Linux系统
- js正则表达式实例(汇总)
- POJ 1244 Slots of Fun(计算几何)
- jquery parent和parents,children和find
- javascript使用栈结构将中缀表达式转换为后缀表达式并计算值
- 【pku2115-C Looooops】拓展欧几里得-不定方程
- mysql时间int日期转换
- java并发4-单例设计方法
- FreeBsdb FAMP Lamp环境
- [Python学习笔记][第五章Python函数设计与使用]
- linux查看与开启ssh
- c语言贪吃蛇详解3.让蛇动起来
- Java-Maven(八):IDEA使用本地maven,并配置远程中央仓库
- 转载泡泡机器人——IMU预积分总结与公式推导2
- 语义化标签和jQuery选择器
- Win7下“回收站已损坏,是否清空该驱动器上的回收站”解决方法
- 2292: Quality of Check Digits 中南多校 暴力枚举