StringJoiner Sql拼接利器

2024-02-07 10:52

本文主要是介绍StringJoiner Sql拼接利器,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1.为什么使用StringJoiner

您还在为使用代码拼接类似的sql占位符而烦恼吗?要生成如下的代码:

(?,?,?,?,?,?,?,?,?,?)

你是使用这种:

StringBuffer sb= new StringBuffer();
sb.append("(");for (int i = 0; i < 10; i++) {if (i == 9) {sb.append("?");} else {sb.append("?").append(",");}}
sb.append(")");

还是使用这种:

StringBuffer sb = new StringBuffer();
sb.append("(");
for (int i = 0; i < 10; i++) {if (i == 0) {sb.append("?");} else {sb.append(",").append("?");}
}
sb.append(")");

而使用StringJoiner,你只需要这样就能生成:

// public StringJoiner(CharSequence delimiter,
//                CharSequence prefix,
//                CharSequence suffix)
StringJoiner joiner = new StringJoiner(",", "(", ")");
for (int i = 0; i < 10; i++) {joiner.add("?");
}

StringJoiner还能合并合并其他的StringJoiner,实现内容的合并。

StringJoiner joiner = new StringJoiner(",", "(", ")");
for (int i = 0; i < 10; i++) {joiner.add("?");
}
StringJoiner joiner1 = new StringJoiner(",", "(", ")");
for (int i = 0; i < 10; i++) {joiner1.add("&");
}
joiner.merge(joiner1);
System.out.println(joiner);
//输出:(?,?,?,?,?,?,?,?,?,?,&,&,&,&,&,&,&,&,&,&)

2.StringJoiner的主要功能

StringJoiner 是 Java 8 引入的一个实用工具类,位于 java.util 包中。它用于构建由分隔符分隔的字符串序列,可以选择性地开始于一个前缀并以一个后缀结束。StringJoiner 是设计来简化多个字符串组合操作的,特别是当你需要创建一个由多个部分组成的字符串时,比如在生成列表、表格或任何由多个元素按照特定格式排列的字符串时。StringJoiner的主要功能如下:

  1. 添加分隔符StringJoiner 的主要功能之一是在添加到 StringJoiner 的每个元素之间自动添加指定的分隔符。这使得构建如逗号分隔值(CSV)或其他由特定字符分隔的字符串变得非常简单和直接。

  2. 可选的前缀和后缀StringJoiner 允许你指定一个可选的前缀和后缀,这些前缀和后缀将被添加到最终构建的字符串的开始和结束位置。这在生成如 JSON 数组或括号包围的列表时非常有用。

  3. 处理空值:默认情况下,如果没有元素添加到 StringJoiner,则它不会添加前缀和后缀,只有在添加了至少一个元素后,前缀和后缀才会出现在结果字符串中。这种行为可以通过使用 setEmptyValue 方法来改变,允许你为一个空的 StringJoiner 实例定义一个自定义的字符串。

  4. 合并StringJoiner 提供了 merge 方法,允许将另一个 StringJoiner 的内容合并到当前的 StringJoiner 中,而不会添加额外的前缀、后缀或分隔符。这在需要组合来自多个源的字符串时非常有用。

  5. 易于使用:与直接使用字符串连接或 StringBuilder 相比,StringJoiner 提供了一种更高级、更易于理解和使用的方式来构建复杂的字符串,尤其是在涉及到多个字符串元素和分隔符时。

3.StringJoiner源码解析

1.主要的属性

//前缀 "("
private final String prefix;
//分隔符 ","
private final String delimiter;
//后缀缀 ")"
private final String suffix;
/** StringBuilder 用于存储当前所有已添加元素的字符串表示,* 如果 StringJoiner 为空,则此字段可能为 null。*/
private StringBuilder value;
  • prefixdelimiter 和 suffix 是在构造时设置的,分别代表前缀、分隔符和后缀。
  • value 是一个 StringBuilder 实例,用于构建和存储最终的字符串。初始时可能为 null,直到添加了第一个元素。

StringJoiner 提供了几个构造函数,允许指定分隔符、前缀和后缀:

 public StringJoiner(CharSequence delimiter,CharSequence prefix,CharSequence suffix) {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");// make defensive copies of argumentsthis.prefix = prefix.toString();this.delimiter = delimiter.toString();this.suffix = suffix.toString();this.emptyValue = this.prefix + this.suffix;}

这个构造函数接受三个参数:delimiterprefixsuffix。所有参数都不能为 null(使用 Objects.requireNonNull 进行检查)。

add方法:

public StringJoiner add(CharSequence newElement) {prepareBuilder().append(newElement);return this;
}private StringBuilder prepareBuilder() {if (value != null) {value.append(delimiter);} else {value = new StringBuilder().append(prefix);}return value;}

  • 如果 valueStringBuilder 实例)不为 null,则意味着之前已经添加过元素,因此在添加新元素之前会先追加分隔符。
  • 如果 value 为 null,则表示这是第一个被添加的元素,因此会创建一个新的 StringBuilder 实例,并先追加前缀。

merge方法如下:

 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;}

最终的字符串是通过 toString 方法生成的:

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();// Now reset the StringBuilder to its original statevalue.setLength(initialLength);return result;}}
}
  • 如果 value 为 null,则返回一个预定义的空值字符串。
  • 否则,会在 valueStringBuilder 实例)上追加后缀,生成最终的字符串,并在操作完成后重置 StringBuilder 的长度,以便移除后缀(这样做是为了保持 value 的状态,以便可以继续添加元素)。

StringJoiner 主要特性:

  • StringJoiner 是不可变的,每次添加元素或合并其他 StringJoiner 实例时,都会在内部更新 StringBuilder 实例。
  • StringJoiner 的设计非常高效,特别适合于构建复杂的字符串,尤其是当涉及到多个部分需要通过特定分隔符连接时。

4.StringJoiner源码

package java.util;/*** {@code StringJoiner} is used to construct a sequence of characters separated* by a delimiter and optionally starting with a supplied prefix* and ending with a supplied suffix.* <p>* Prior to adding something to the {@code StringJoiner}, its* {@code sj.toString()} method will, by default, return {@code prefix + suffix}.* However, if the {@code setEmptyValue} method is called, the {@code emptyValue}* supplied will be returned instead. This can be used, for example, when* creating a string using set notation to indicate an empty set, i.e.* <code>"{}"</code>, where the {@code prefix} is <code>"{"</code>, the* {@code suffix} is <code>"}"</code> and nothing has been added to the* {@code StringJoiner}.** @apiNote* <p>The String {@code "[George:Sally:Fred]"} may be constructed as follows:** <pre> {@code* StringJoiner sj = new StringJoiner(":", "[", "]");* sj.add("George").add("Sally").add("Fred");* String desiredString = sj.toString();* }</pre>* <p>* A {@code StringJoiner} may be employed to create formatted output from a* {@link java.util.stream.Stream} using* {@link java.util.stream.Collectors#joining(CharSequence)}. For example:** <pre> {@code* List<Integer> numbers = Arrays.asList(1, 2, 3, 4);* String commaSeparatedNumbers = numbers.stream()*     .map(i -> i.toString())*     .collect(Collectors.joining(", "));* }</pre>** @see java.util.stream.Collectors#joining(CharSequence)* @see java.util.stream.Collectors#joining(CharSequence, CharSequence, CharSequence)* @since  1.8
*/
public final class StringJoiner {private final String prefix;private final String delimiter;private final String suffix;/** StringBuilder value -- at any time, the characters constructed from the* prefix, the added element separated by the delimiter, but without the* suffix, so that we can more easily add elements without having to jigger* the suffix each time.*/private StringBuilder value;/** By default, the string consisting of prefix+suffix, returned by* toString(), or properties of value, when no elements have yet been added,* i.e. when it is empty.  This may be overridden by the user to be some* other value including the empty String.*/private String emptyValue;/*** Constructs a {@code StringJoiner} with no characters in it, with no* {@code prefix} or {@code suffix}, and a copy of the supplied* {@code delimiter}.* If no characters are added to the {@code StringJoiner} and methods* accessing the value of it are invoked, it will not return a* {@code prefix} or {@code suffix} (or properties thereof) in the result,* unless {@code setEmptyValue} has first been called.** @param  delimiter the sequence of characters to be used between each*         element added to the {@code StringJoiner} value* @throws NullPointerException if {@code delimiter} is {@code null}*/public StringJoiner(CharSequence delimiter) {this(delimiter, "", "");}/*** Constructs a {@code StringJoiner} with no characters in it using copies* of the supplied {@code prefix}, {@code delimiter} and {@code suffix}.* If no characters are added to the {@code StringJoiner} and methods* accessing the string value of it are invoked, it will return the* {@code prefix + suffix} (or properties thereof) in the result, unless* {@code setEmptyValue} has first been called.** @param  delimiter the sequence of characters to be used between each*         element added to the {@code StringJoiner}* @param  prefix the sequence of characters to be used at the beginning* @param  suffix the sequence of characters to be used at the end* @throws NullPointerException if {@code prefix}, {@code delimiter}, or*         {@code suffix} is {@code null}*/public StringJoiner(CharSequence delimiter,CharSequence prefix,CharSequence suffix) {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");// make defensive copies of argumentsthis.prefix = prefix.toString();this.delimiter = delimiter.toString();this.suffix = suffix.toString();this.emptyValue = this.prefix + this.suffix;}/*** Sets the sequence of characters to be used when determining the string* representation of this {@code StringJoiner} and no elements have been* added yet, that is, when it is empty.  A copy of the {@code emptyValue}* parameter is made for this purpose. Note that once an add method has been* called, the {@code StringJoiner} is no longer considered empty, even if* the element(s) added correspond to the empty {@code String}.** @param  emptyValue the characters to return as the value of an empty*         {@code StringJoiner}* @return this {@code StringJoiner} itself so the calls may be chained* @throws NullPointerException when the {@code emptyValue} parameter is*         {@code null}*/public StringJoiner setEmptyValue(CharSequence emptyValue) {this.emptyValue = Objects.requireNonNull(emptyValue,"The empty value must not be null").toString();return this;}/*** Returns the current value, consisting of the {@code prefix}, the values* added so far separated by the {@code delimiter}, and the {@code suffix},* unless no elements have been added in which case, the* {@code prefix + suffix} or the {@code emptyValue} characters are returned** @return the string representation of this {@code StringJoiner}*/@Overridepublic 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 initialLengthvalue.setLength(initialLength);return result;}}}/*** Adds a copy of the given {@code CharSequence} value as the next* element of the {@code StringJoiner} value. If {@code newElement} is* {@code null}, then {@code "null"} is added.** @param  newElement The element to add* @return a reference to this {@code StringJoiner}*/public StringJoiner add(CharSequence newElement) {prepareBuilder().append(newElement);return this;}/*** Adds the contents of the given {@code StringJoiner} without prefix and* suffix as the next element if it is non-empty. If the given {@code* StringJoiner} is empty, the call has no effect.** <p>A {@code StringJoiner} is empty if {@link #add(CharSequence) add()}* has never been called, and if {@code merge()} has never been called* with a non-empty {@code StringJoiner} argument.** <p>If the other {@code StringJoiner} is using a different delimiter,* then elements from the other {@code StringJoiner} are concatenated with* that delimiter and the result is appended to this {@code StringJoiner}* as a single element.** @param other The {@code StringJoiner} whose contents should be merged*              into this one* @throws NullPointerException if the other {@code StringJoiner} is null* @return This {@code StringJoiner}*/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;}/*** Returns the length of the {@code String} representation* of this {@code StringJoiner}. Note that if* no add methods have been called, then the length of the {@code String}* representation (either {@code prefix + suffix} or {@code emptyValue})* will be returned. The value should be equivalent to* {@code toString().length()}.** @return the length of the current value of {@code StringJoiner}*/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());}
}

这篇关于StringJoiner Sql拼接利器的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/687477

相关文章

mysql删除无用用户的方法实现

《mysql删除无用用户的方法实现》本文主要介绍了mysql删除无用用户的方法实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 1、删除不用的账户(1) 查看当前已存在账户mysql> select user,host,pa

使用Dify访问mysql数据库详细代码示例

《使用Dify访问mysql数据库详细代码示例》:本文主要介绍使用Dify访问mysql数据库的相关资料,并详细讲解了如何在本地搭建数据库访问服务,使用ngrok暴露到公网,并创建知识库、数据库访... 1、在本地搭建数据库访问的服务,并使用ngrok暴露到公网。#sql_tools.pyfrom

MySQL中实现多表查询的操作方法(配sql+实操图+案例巩固 通俗易懂版)

《MySQL中实现多表查询的操作方法(配sql+实操图+案例巩固通俗易懂版)》本文主要讲解了MySQL中的多表查询,包括子查询、笛卡尔积、自连接、多表查询的实现方法以及多列子查询等,通过实际例子和操... 目录复合查询1. 回顾查询基本操作group by 分组having1. 显示部门号为10的部门名,员

Golang中拼接字符串的6种方式性能对比

《Golang中拼接字符串的6种方式性能对比》golang的string类型是不可修改的,对于拼接字符串来说,本质上还是创建一个新的对象将数据放进去,主要有6种拼接方式,下面小编就来为大家详细讲讲吧... 目录拼接方式介绍性能对比测试代码测试结果源码分析golang的string类型是不可修改的,对于拼接字

MyBatis-Plus中静态工具Db的多种用法及实例分析

《MyBatis-Plus中静态工具Db的多种用法及实例分析》本文将详细讲解MyBatis-Plus中静态工具Db的各种用法,并结合具体案例进行演示和说明,具有很好的参考价值,希望对大家有所帮助,如有... 目录MyBATis-Plus中静态工具Db的多种用法及实例案例背景使用静态工具Db进行数据库操作插入

MySQL中COALESCE函数示例详解

《MySQL中COALESCE函数示例详解》COALESCE是一个功能强大且常用的SQL函数,主要用来处理NULL值和实现灵活的值选择策略,能够使查询逻辑更清晰、简洁,:本文主要介绍MySQL中C... 目录语法示例1. 替换 NULL 值2. 用于字段默认值3. 多列优先级4. 结合聚合函数注意事项总结C

通过ibd文件恢复MySql数据的操作方法

《通过ibd文件恢复MySql数据的操作方法》文章介绍通过.ibd文件恢复MySQL数据的过程,包括知道表结构和不知道表结构两种情况,对于知道表结构的情况,可以直接将.ibd文件复制到新的数据库目录并... 目录第一种情况:知道表结构第二种情况:不知道表结构总结今天干了一件大事,安装1Panel导致原来服务

mysql关联查询速度慢的问题及解决

《mysql关联查询速度慢的问题及解决》:本文主要介绍mysql关联查询速度慢的问题及解决方案,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录mysql关联查询速度慢1. 记录原因1.1 在一次线上的服务中1.2 最终发现2. 解决方案3. 具体操作总结mysql

Linux搭建Mysql主从同步的教程

《Linux搭建Mysql主从同步的教程》:本文主要介绍Linux搭建Mysql主从同步的教程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录linux搭建mysql主从同步1.启动mysql服务2.修改Mysql主库配置文件/etc/my.cnf3.重启主库my

MySql中的数据库连接池详解

《MySql中的数据库连接池详解》:本文主要介绍MySql中的数据库连接池方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录mysql数据库连接池1、概念2、为什么会出现数据库连接池3、原理4、数据库连接池的提供商5、DataSource数据源6、DBCP7、C