java8新增StringJoiner用法

1. 添加元素

public void () {
    StringJoiner joiner = new StringJoiner(",", PREFIX, SUFFIX);
    joiner.add("Red")
      .add("Green")
      .add("Blue");
 
    assertEquals(joiner.toString(), "[Red,Green,Blue]");
}

2. 使用for循环添加内容

public void whenAddingListElements_thenJoinedListElements() {
    List<String> rgbList = new ArrayList<>();
    rgbList.add("Red");
    rgbList.add("Green");
    rgbList.add("Blue");
 
    StringJoiner rgbJoiner = new StringJoiner(
      ",", PREFIX, SUFFIX);
 
    for (String color : rgbList) {
        rgbJoiner.add(color);
    }
 
    assertEquals(rgbJoiner.toString(), "[Red,Green,Blue]");
}

 

使用构造方式

private String PREFIX = "[";
private String SUFFIX = "]";
 

public void whenEmptyJoinerWithoutPrefixSuffix_thenEmptyString() {
    StringJoiner joiner = new StringJoiner(",");
  
    assertEquals(0, joiner.toString().length());
}
 

public void whenEmptyJoinerJoinerWithPrefixSuffix_thenPrefixSuffix() {
    StringJoiner joiner = new StringJoiner(
      ",", PREFIX, SUFFIX);
  
    assertEquals(joiner.toString(), PREFIX + SUFFIX);
}

 

合并Joiner

public void whenMergingJoiners_thenReturnMerged() {
    StringJoiner rgbJoiner = new StringJoiner(
      ",", PREFIX, SUFFIX);
    StringJoiner cmybJoiner = new StringJoiner(
      "-", PREFIX, SUFFIX);
 
    rgbJoiner.add("Red")
      .add("Green")
      .add("Blue");
    cmybJoiner.add("Cyan")
      .add("Magenta")
      .add("Yellow")
      .add("Black");
 
    rgbJoiner.merge(cmybJoiner);
 
    assertEquals(
      rgbJoiner.toString(), 
      "[Red,Green,Blue,Cyan-Magenta-Yellow-Black]");
}

使用流

@Test
public void whenUsedWithinCollectors_thenJoined() {
    List<String> rgbList = Arrays.asList("Red", "Green", "Blue");
    String commaSeparatedRGB = rgbList.stream()
      .map(color -> color.toString())
      .collect(Collectors.joining(","));
 
    assertEquals(commaSeparatedRGB, "Red,Green,Blue");
}

3、总结

分割字符串使用StringJoiner方式很不错,也可以使用流的方式,两个字符串拼接merge也挺好用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值