在JDK 8中连接字符串

JDK 8引入了语言功能,例如lambda表达式 ,甚至是新的Date / Time API ,这些都会改变我们编写Java应用程序的方式。 但是,还有一些新的API和功能可能不太“改变游戏规则”,但仍为Java编程语言带来了更大的便利性和表现力。 在本文中,我将介绍这些较小的功能之一,并研究在JDK 8中轻松连接多个String的能力。

JDK 8中连接多个String的最简单方法也许是通过遍在Java类String上的两个新的静态方法: join(CharSequence,CharSequence…)join(CharSequence,Iterable) 。 接下来的两个代码清单演示了应用这两个String.join方法有多么容易。

使用String.join(CharSequence,CharSequence ...)

/**
 * Words associated with the blog at http://marxsoftware.blogspot.com/ in array.
 */
private final static String[] blogWords = {"Inspired", "by", "Actual", "Events"};

/**
 * Demonstrate joining multiple Strings using static String
 * "join" method that accepts a "delimiter" and a variable
 * number of Strings (or an array of Strings).
 */
private static void demonstrateStringJoiningArray()
{
   final String blogTitle = String.join(" ", blogWords);
   out.println("Blog Title: " + blogTitle);

   final String postTitle = String.join(" ", "Joining", "Strings", "in", "JDK", "8");
   out.println("Post Title: " + postTitle);
}

使用String.join(CharSequence,Iterable)

/**
 * Pieces of a Media Access Control (MAC) address.
 */
private final static List<String> macPieces;

static
{
   macPieces = new ArrayList<>();
   macPieces.add("01");
   macPieces.add("23");
   macPieces.add("45");
   macPieces.add("67");
   macPieces.add("89");
   macPieces.add("ab");
};

/**
 * Demonstrate joining multiple Strings using static String
 * "join" method that accepts a "delimiter" and an Iterable
 * on Strings.
 */
private static void demonstrateStringJoiningIterable()
{
   final String macAddress = String.join(":", macPieces);
   out.println("MAC Address: " + macAddress);
}

运行以上两个代码清单的输出是:

Blog Title: Inspired by Actual Events
Post Title: Joining Strings in JDK 8
MAC Address: 01:23:45:67:89:ab

使用两个静态String.join方法是组合字符串的简便方法,但是JDK 8引入的StringJoiner类提供了更多功能和灵活性。 下一个代码清单演示了如何实例化StringJoiner并将其传递给指定的定界符(小数点),前缀(打开括号)和后缀(关闭括号)。

简单的字符串连接器使用

/**
 * Demonstrate joining multiple Strings using StringJoiner
 * with specified prefix, suffix, and delimiter.
 */
private static void demonstrateBasicStringJoiner()
{
   // StringJoiner instance with decimal point for delimiter, opening
   // parenthesis for prefix, and closing parenthesis for suffix.
   final StringJoiner joiner = new StringJoiner(".", "(", ")");
   joiner.add("216");
   joiner.add("58");
   joiner.add("216");
   joiner.add("206");
   final String ipAddress = joiner.toString();
   out.println("IP Address: " + ipAddress);
}

运行上面的代码将以下字符串打印到标准输出:“ IP地址:(216.58.216.206)”

StringJoiner是一种特别有吸引力的方法,在这种情况下,正在使用StringBuilder将定界字符添加到要作为某种迭代类型的一部分而构建的String中。 在这种情况下,通常有必要在上一次迭代中删除添加到该构建器末尾的额外字符。 StringJoiner非常“聪明”,只在要连接的字符串之间添加定界符,而不在最后一个字符串后添加定界符。 连续调用add(CharSequence)方法看起来与StringBuilder / StringBuffer API非常相似。

我将在本文中介绍的最终的JDK 8引入的用于连接String的方法是将流支持的集合与连接 收集器一起使用归约操作 )。 在下一个代码清单中对此进行了演示,其输出与用于通过String.join打印MAC地址的String.join方法相同,该方法接受Iterable作为其第二个参数。

字符串与收藏集的流连接

/**
 * Demonstrate joining Strings in a collection via that collection's
 * Stream and use of the Joining Collector.
 */
private static void demonstrateStringJoiningWithCollectionStream()
{
   final String macAddress =
      macPieces.stream().map(
         piece -> piece.toString()).collect(Collectors.joining(":"));
   out.println("MAC Address: " + macAddress);
}

如果开发人员希望能够为连接的字符串提供前缀和后缀,而不必连续调用add使用StringJoiner连接String所需的方法,则Collectors.joining(CharSequence,CharSequence,CharSequence)方法是完美的选择。 下一个代码示例显示了上面的IP地址示例,用于演示StringJoiner ,但这一次是使用集合,流和StringJoiner收集器实现的。 输出与前面的示例相同,无需为每个要连接的String指定add(CharSequence)

字符串与Collection的流,前缀和后缀联接

/**
 * Demonstrate joining Strings in a collection via that collection's
 * Stream and use of a Joining Collector that with specified prefix 
 * and suffix.
 */
private static void demonstrateStringJoiningWithPrefixSuffixCollectionStream()
{
   final List<String> stringsToJoin = Arrays.asList("216", "58", "216", "206");
   final String ipAddress =
      stringsToJoin.stream().map(
         piece -> piece.toString()).collect(Collectors.joining(".", "(", ")"));
   out.println("IP Address: " + ipAddress);
}

这篇博客文章介绍了JDK 8提供的三种连接字符串的方法:

  1. 静态String.join方法
  2. StringJoiner实例
  3. 加入收集器的收集流

翻译自: https://www.javacodegeeks.com/2015/02/joining-strings-in-jdk-8.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值