JAVA8——StringJoiner类
引言:在阅读项目代码是,突然看到了StringJoiner这个类的使用,感觉很有意思,对实际开发中也有用,实际上是运用了StringBuilder的一个拼接字符串的封装处
介绍
StringJoiner是Java8新出的一个类,用于构造由分隔符分隔的字符序列,并可选择性地从提供的前缀开始和以提供的后缀结尾。省的我们开发人员再次通过StringBuffer或者StingBuilder拼接。
我们查看一下一下代码,试着猜一下。
StringJoiner sj = new StringJoiner(":", "[", "]");
sj.add("George").add("Sally").add("Fred");
String desiredString = sj.toString();
System.out.println(desiredString);
System.out.println(sj.length());
代码输出为[George:Sally:Fred] 长度19
源码
这个类的源码很简单,大家很容易就可以看明白。
package java.util;
public final class StringJoiner {
private final String prefix;//前缀
private final String delimiter;//间隔符
private final String suffix;//后缀
private StringBuilder value;//值
private String emptyValue;//空值
public StringJoiner(CharSequence delimiter) {
this(delimiter, "", "");//默认前缀和后缀为"",重载调用
}
public StringJoiner(CharSequence delimiter,
CharSequence prefix,
CharSequence suffix) {
//间隔符,前缀和后缀判断是否为null,null将抛出异常
Objects.requireNonNull(prefix, "The prefix must not be null");
Objects.requireNonNull(delimiter, "The delimiter must not be null");
Objects.requireNonNull(suffix, "The suffix must not be null");
// 成员变量赋值
this.prefix = prefix.toString();
this.delimiter = delimiter.toString();
this.suffix = suffix.toString();
this.emptyValue = this.prefix + this.suffix;//空值被设置为只有前后缀
}
//设置空值,检查是否为null
public StringJoiner setEmptyValue(CharSequence emptyValue) {
this.emptyValue = Objects.requireNonNull(emptyValue,
"The empty value must not be null").toString();
return this;
}
@Override
public String toString() {
if (value == null) {
return emptyValue;//没有值将返回空值或者后续设置的空值
} else {
if (suffix.equals("")) {
return value.toString();//后缀为""直接返回字符串,不用添加
} else {
//后缀不为"",添加后缀,然后直接返回字符串,修改长度
int initialLength = value.length();
String result = value.append(suffix).toString();
// reset value to pre-append initialLength
value.setLength(initialLength);
return result;
}
}
}
初始化,先添加前缀,有了之后每次先添加间隔符,StringBuilder后续append字符串
public StringJoiner add(CharSequence newElement) {
prepareBuilder().append(newElement);
return this;
}
//合并StringJoiner,注意后面StringJoiner 的前缀就不要了,后面的appen进来
public StringJoiner merge(StringJoiner other) {
Objects.requireNonNull(other);
if (other.value != null) {
final int length = other.value.length();
// lock the length so that we can seize the data to be appended
// before initiate copying to avoid interference, especially when
// merge 'this'
StringBuilder builder = prepareBuilder();
builder.append(other.value, other.prefix.length(), length);
}
return this;
}
//初始化,先添加前缀,有了之后每次先添加间隔符
private StringBuilder prepareBuilder() {
if (value != null) {
value.append(delimiter);
} else {
value = new StringBuilder().append(prefix);
}
return value;
}
public int length() {
// Remember that we never actually append the suffix unless we return
// the full (present) value or some sub-string or length of it, so that
// we can add on more if we need to.
//不忘添加后缀的长度
return (value != null ? value.length() + suffix.length() :
emptyValue.length());
}
}
JAVA8——StringJoiner类的更多相关文章
- JAVA8—————StringJoiner类
JAVA8——StringJoiner类引言:在阅读项目代码是,突然看到了StringJoiner这个类的使用,感觉很有意思,对实际开发中也有用,实际上是运用了StringBuilder的一个拼接字符 ...
- 使用Java8 Files类读写文件
Java8 Files类的newBufferedReader()和newBufferedWriter()方法 这两个方法接受Path类型的参数.Path 类是Java8 NIO中的接口.可以由Path ...
- java8时间类
java8引入了一套全新的时间日期API 新的时间及日期API位于java.time中java.time包中的是类是不可变且线程安全的. 下面是一些关键类 LocalDateTime // ...
- Java8 Collectors类的静态工厂方法
预定义收集器的功能,就是那些可以从Collectors类提供的工厂方法(例如grouping By)创建的收集器. 它们主要提供了三大功能: •将流元素归约和汇总为一个值 •元素分组 •元素分区 •c ...
- java8时间类API安全问题(赠送新的时间工具类哟)
LocalDateTime等新出的日期类全是final修饰的类,不能被继承,且对应的日期变量都是final修饰的,也就是不可变类.赋值一次后就不可变,不存在多线程数据问题. simpleDateFor ...
- spring boot添加 LocalDateTime 等 java8 时间类序列化和反序列化的支持
由于项目将原有的 Date类型的字段改造为 LocalDate,LocalDateTime,LocalTime 类型, 发现 spring 对项目的时间格式无法自动转换,故需手动配置下. 在sp ...
- Java8 Optional类
概述 到目前为止,著名的NullPointerException是导致Java应用程序失败的最常见原因.过去,为了解决空指针异常,Google公司著名的Guava项目引入了Optional类,Guav ...
- 详解Java8 Optional类{最全}
1:Optional 1.1 概述 Optional 类主要解决的问题是臭名昭著的空指针异常(NullPointerException),提供了一些的方法代替过去的if-else处理逻辑,并与Stre ...
- Java8 Optional类使用小结
Optional类的Javadoc描述如下: 这是一个可以为null的容器对象.如果值存在则isPresent()方法会返回true,调用get()方法会返回该对象. of: 为非null的值创建一 ...
- Java8 Period 类与 Duration 类 用法详解
引言 Java 8 中引入了两个与日期相关的新类: Period :基于日期值 Duration:基于时间值 它们最大的作用就不需要你自己复杂的计算关于两个年月日之间的相差的时间或日期啦. Perio ...
随机推荐
- Solr的学习使用之(七)Solr高级查询facet、facet.pivot简介 - OnTheRoad_Lee
http://martin3000.iteye.com/blog/1330106 1 .什么是Faceted Search Facet['fæsɪt]很难翻译,只能靠例子来理解了.Solr作者Yoni ...
- JDK7新特性之G1 GC
Garbage-first garbage collector,简称G1 GC,是最终将用于代替Concurrent Mark-Sweep garbage collector(CMS GC)的新一代垃 ...
- 想学习建个网站?WAMP Server助你在Windows上快速搭建PHP集成环境
我想只要爬过几天网的同学都会知道PHP吧,异次元的新版本就是基于PHP的WordPress程序制造出来的,还有国内绝大部分论坛都是PHP的哦.据我所知很多同学都想要试着学习一下PHP,无奈要在Wind ...
- Tornado框架之基础(一)
知识点 了解什么是Tornado框架 了解Tornado与Django的区别 Tornado的安装 了解Tornado的原理 掌握Tornado的基本写法 掌握Tornado的基本模块 tornado ...
- Lambda【1】-- List相关Lambda表达式使用(上篇)
Lambda在jdk1.8里面已经很好用了,在这里不讲底层的实现,只有简单的用法,会继续补全. 首先一个list我们要使用lambda的话,需要使用它的stream()方法,获取流,才能使用后续的方法 ...
- LiV-GS: LiDAR-Vision Integration for 3D Gaussian Splatting SLAM in Outdoor Environments
arxiv |哈工大发布 LiV-GS:户外环境中基于3D高斯泼溅的LiDAR-视觉集成SLAM系统 [LiV-GS: LiDAR-Vision Integration for 3D Gaussian ...
- Uniapp input的maxlength问题
前情 uni-app是我很喜欢的跨平台框架,它能开发小程序,H5,APP(安卓/iOS),对前端开发很友好,自带的IDE让开发体验也很棒,公司项目就是主推uni-app. 坑位 最近在做一个input ...
- 鸿蒙UI开发快速入门 —— part08: 组件状态管理之@Provide/@Consume装饰器
1.说在前面的话 在此之前,我们已经先后学习了三个装饰器:@State.@Props.@Link,它们的功能和使用场景分别是什么?暂停会议一下. 我们目前已经可以处理组件内状态(@State),也可以 ...
- x509.MarshalSm2PrivateKey
根据搜索结果,x509.MarshalSm2PrivateKey 函数需要两个参数:一个 *sm2.PrivateKey 和一个 []byte 类型的密码.以下是使用 x509.MarshalSm2P ...
- SpringBoot结合Liquibase实现数据库变更管理
https://juejin.cn/post/7171232605478584328 https://juejin.cn/post/7170857098538909732 前言 研发过程中经常涉及到数 ...